Search code examples
javascriptdebugginggoogle-chrome-devtoolsfirefox-developer-tools

createElement(script)/appendChild how to debug added script?


    var js = document.createElement("script");
    js.type = "text/javascript";
    js.innerHTML = layout[i].text;
    document.body.appendChild(js);

I am adding a script like that, notice there is no src, but innerHTML instead, a script is fetched on demand with XMLHttpRequest. Unfortunately the script does not appear in the dev tools, not in Chrome not in Firefox.

How to append a script from a source string so that I can still debug it in the devtools?


Solution

  • To be able to debug dynamically added scripts in Chrome, you need to append //# sourceURL=test_file_name.js at the end of the script that you want to debug, like below

    var js = document.createElement("script");
    js.type = "text/javascript";
    js.innerHTML = layout[i].text + "//# sourceURL=test_file_name.js";
    document.body.appendChild(js);
    

    Now, if you open the source tab in Dev console, you will find test_file_name.js under the (no domain) section (normally). I just verified it in Chrome version 67.0.X

    I believe the same should work on Firefox as well,

    Refer these links also,

    Chrome Dev Tools

    sourceMappingURL and sourceURL syntax changed

    Update : This doesn't work in firefox. There are several bugs created for this issue, but no fix so far, script tag using sourceURL doesn't appear in debugger sources pane