0

In mytest.html I include this:

<html><head>
<script type="text/javascript" src="/myjavascript.js?foo=bar"></script>
</head>
<body>Hi</body>
</html>

In the myjavascript.js

alert(this.location.search);

This shows the query string mytest.html but I want query string of the javascript itself "foo=bar" or just "bar".

Any ideas as to how to do this would be great. (I am thinking maybe I need to read the html for script element and parse that text. But I am hoping this is an easier way.)

I can use JQuery to do this as well if there is an easy way.

JeffJak
  • 2,008
  • 5
  • 28
  • 40

3 Answers3

1

When the script is running, it is the last thing that has loaded on the page. In particular, this also makes it the last script element at the current time.

So, with that in mind, try this:

var scripts = document.getElementsByTagName('script'),
    lastscriptsrc = scripts[scripts.length-1].getAttribute("src"),
    search = lastscriptsrc.substr(lastscriptsrc.indexOf("?"));

EDIT: You can also one-line it, though it's less readable:

var search = [].pop.apply(document.getElementsByTagName('script')).getAttribute("src").replace(/.*\?/,"");
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • would `defer="defer"` possibly affect this ? – Mark Broadhurst Apr 02 '13 at 14:43
  • "When the script is running, it is the last thing that has loaded on the page." — *Usually*. That isn't always the case; script elements may be added anywhere with DOM. – Quentin Apr 02 '13 at 14:43
  • @SaintGerbil — It could do. – Quentin Apr 02 '13 at 14:44
  • @Quentin But when you're talking about inline javascript (where the Javascript is blocking the rest of the HTML page from being parsed/rendered), it is currently the last element. – Ian Apr 02 '13 at 14:47
0

I accepted Kolink answer. As the comments notes, I am not 100% confident that it will be the last script (appears to work). So the below is more explicit about which script src.

Here was my JQuery answer using Kolink answer to help me:

var scriptsrc = $("script[src*='myjavascript']").attr("src");
var search = scriptsrc.substr(scriptsrc.indexOf("?"));
alert("search:" + search);

Thank you so much for help on this.

JeffJak
  • 2,008
  • 5
  • 28
  • 40
0

Try this

var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arr = new Array();
arr = spQrStr.split('&');
for (var i=0;i<arr.length;i++)
{
    var queryvalue = arr[i].split('=');
    alert("Name: "+queryvalue[0]+" Value: "+queryvalue[1]);
}
Syed Mohamed
  • 1,339
  • 1
  • 15
  • 23