2

How can I read get parameters passed to a JS file like so:

<script type="text/javascript" src="/script.js?p1=hello&p2=world"></script>

In the same file (script.js) I want to read the p1 and p2 values like:

var p1 = params["p1"];

I'd rather avoid a method that getElementById's or uses the dom anyway. thanks.

Gal
  • 23,122
  • 32
  • 97
  • 118
  • Would it be possible for you to make a PHP wrapper that echoes the get parameters into the .js file? – pimvdb Aug 08 '11 at 15:53
  • This might be interesting: http://stackoverflow.com/questions/4716612/how-do-i-get-query-string-value-from-script-path – pimvdb Aug 08 '11 at 15:54
  • @pimvdb no, the purpose is making it front-end only. – Gal Aug 08 '11 at 15:55
  • Take a look at this [enter link description here][1] [1]: http://stackoverflow.com/questions/2328864/calling-url-parameters-within-a-js-file – Alexey Aug 08 '11 at 16:00

2 Answers2

3

No magic that I'm aware of here... As the script is loaded, the tag is added to the dom tree and you can read from it using document.getElementsByTagName('script') and then parse the results.

Full code given here : http://feather.elektrum.org/book/src.html

Gad
  • 41,526
  • 13
  • 54
  • 78
  • Thanks, I wanted to make sure there wasn't anything similar to window.location that pertains to the .js file itself. Used getElementById eventually. – Gal Aug 08 '11 at 16:07
-1

See this answer. You then have to parse the result yourself.

How to check for script src match, then reassign src

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • This will not work, cause `script[i].src` contains full URL with all params, so you don't have loop through all scripts' srcs if you already know query string – vladkras Apr 27 '16 at 19:28