djechlin
djechlin

Reputation: 60758

Run remote javascript from browser without modifying DOM

The only way I know to run remote javascript is to add a tag like

<script src="example.com/ascript.js"></script>

Is it possible to do a similar thing in Javascript without needing to modify the DOM as part of the call?

Upvotes: 0

Views: 59

Answers (1)

jfriend00
jfriend00

Reputation: 707218

If what you're asking is whether it's possible to dynamically load Javascript from a remote source and run it without inserting a script tag, then there are some ways to do that (though it is unclear why it's a burden to momentarily insert a <script> tag and let the system load and run the code all by itself).

In a nutshell, you can load some Javascript into a string using an Ajax call and you can then run eval() on that string to execute it. This will have all the usual security caveats about running Javascript that comes from an external source in the context of your page.

The Ajax call (unlike <script> tags inserted into the DOM) will be subject to same-origin limitations unless the target site enables access with CORS.

For example:

fetch(someScriptURL).then(function(data) {
    eval(data);
});

Upvotes: 2

Related Questions