Executing a JavaScript file directly from the browser

前端 未结 6 1089
攒了一身酷
攒了一身酷 2021-01-31 04:31

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

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

6条回答
  •  时光说笑
    2021-01-31 05:14

    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, 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); })();
    

提交回复
热议问题