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

André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120
  • 1
    it'd be in the `url` var? – Marc B Nov 07 '13 at 14:03
  • possible duplicate of [How can I get query string values?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values) – Marc B Nov 07 '13 at 14:04
  • http://stackoverflow.com/questions/1034621/get-current-url-with-javascript – Christos Nov 07 '13 at 14:04
  • 2
    Neither of those two "duplicates" answer this question, guys... – Niet the Dark Absol Nov 07 '13 at 14:05
  • [I think this will help](http://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script) – musefan Nov 07 '13 at 14:05
  • If the script is executed immediately (no async/defer), you can use the same method as described here to get access to the script element: http://ejohn.org/blog/degrading-script-tags/ – CBroe Nov 07 '13 at 14:05

1 Answers1

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.

Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592