0

So I have a script that is loaded dynamically into the page as so:

<div>
    <script>
        var url = 'http://example.com/scripts/myscript.js?foo=bar';
        document.write('<scr'+'ipt type=\"text/javascript\" src=\""+url+"\"></scri'+'pt>')
    </script>;
</div>

I need to know, if there is a way, inside the myscript.js i am loading, to access the url to get the query string.

Thanks

6

1 Answer 1

3

When a script is running (unless you add defer or async attributes), it will always be the last element on the page so far. You can therefore take advantage of this fact:

var scripts = document.getElementsByTagName('script'),
    currentScript = scripts[scripts.length-1],
    myScriptURL = currentScript.getAttribute("src");

You can then process that myScriptURL variable to extract query string paramters, as demonstrated in this question.

Sign up to request clarification or add additional context in comments.

2 Comments

even if the script is injected at a later time, and has some script tags below?
That would count as deferring the script, which causes this method to fail.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.