本文介绍了直接从浏览器中执行JavaScript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来像一个小问题,但我真的需要知道的。

This sounds like a trivia question but I really need to know.

如果你把一个HTML文件的URL在浏览器的地址栏,它将呈现该HTML。这是一个浏览器的全部目的。

If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.

如果你给它一个JPG或SWF文件,甚至是PDF,它会做正确的事情,对于那些数据类型。

If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.

但是,如果你给它一个JavaScript文件的URL,它会的显示的该文件的文本。我想要的是直接执行该文件。

But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.

现在,我知道,如果你使用了的javascript:的协议,它将执行的文本的网址,而不是我需要什么。

Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.

我能有URL指向包括一个HTML文件中的单个<脚本> 标记,依次指向JavaScript文件,但对于隐匿性原因我自己,我不能这样做。

I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.

如果在 http://example.com/file.js 完全由文件

 alert("it ran");

和我把那个URL的地址栏,我想它跑​​,弹出的警告。

And I put that URL in the Location bar, I want "it ran" to pop up as an alert.

我怀疑,这是可能的,但我希望-反对,希望有一个页眉或MIME类型或类似的东西,我可以设置并奇迹般地做到这一点。

I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.

推荐答案

这是不可能的。浏览器不知道JavaScript的应该运行在什么情况下;例如,什么是窗口的属性?如果你认为它可以想出一些随机的默认值,约文件的行为是什么?如果有人 document.body.innerHTML =富会发生什么?

This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?

的JavaScript,不像图像或HTML页面,是依赖于它运行的上下文。这种情况下可能是一个HTML页面,或者它可以是一个节点服务器环境中,或者它甚至可以是Windows脚本宿主。但如果你只是浏览到一个URL,浏览器不知道什么情况下应该运行该脚本。

JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.

作为一种变通方法,或者使用关于:空白作为主机页面。然后,你可以插入脚本到文档中,给它适当的执行上下文,通过在地址栏粘贴以下内容:

As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:

javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();

这篇关于直接从浏览器中执行JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 02:58