Reputation: 53
The usual way of adding Javascript to a page is by adding it to the document's <body>
or <head>
in either static HTML or something generated server-side.
I would like to generate dynamic Javascript, and add it to the document in a dynamic fashion; that is on-demand and during run-time. For example Javascript code transmitted over a WebSocket.
One option is to create a script element, add the string with script contents to the .text property, while finally adding the script to the document, like this:
var scriptContent = 'console.log("dynamic script");';
var s = document.createElement('script');
s.text = scriptContent;
document.body.appendChild(s);
This would work, but my concern is that the script is executed with the same URL/origin as the HTML document. Whereas, if it would be a separate file, invoked with the s.src parameter, it would show up under its own URL when looking at the browser console.
Why is this at all relevant? When using the browser console to debug and inspect, it usually tells you the name of the script and the line/column of the message printed to the console. For example, when opening the console, one might several console messages, with on the right side the origin and line/column information:
<domainname>:1:1
separate_js_file.js:14:20
This is the behavior that I desire because it makes it easy to distinguish what script has written something to the console. However, if adding Javascript dynamically to the page, it all gets 'advertised' under the main document, usually printed by the domainname, like domain.com:1:1
.
What I would like is to change/pretend/masquerade the origin of the script, to pretend it was an external script. This way, not all lines printed to the console would be from origin domain.com:<line>:<column>
but instead would be called specifically, like module1:<line>:<column>
.
Is this at all possible?
Upvotes: 5
Views: 250
Reputation: 4868
I think you can append a source map at the end of the dynamic JS.
//# sourceURL=http://example.com/path/to/your/sourcemap.map
This works when using eval statements in Firefox and in with both injected script tags and evals in chrome. Might be a way to make Firefox understand it via script tags as well.
See https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map for the details.
See also Can't see dynamically loaded code in Chrome Developer Tools 22 for some more details.
Upvotes: 2