views:

335

answers:

2

http://mycloud.net/js/file.js#foo=bar

I'm trying to load a cross domain javascript file, and want to pass a variable along on the query string. I have seen the above '#' method used, but am unsure of how to extract the 'foo' value from within the file.js. Any clues how to handle this without the aid of server side help?

Thanks.

+1  A: 

The only way for the script to get hold of the value in the bookmark, would be to somehow find it's script tag in the document and extract it from the scr attribute.

The bookmark part of the URL isn't sent along in the request, so you can't pick it up using server side code either.

Guffa
+2  A: 

Well, there is actually a way to get the current script, e.g.:

// external script
(function () {
  var scripts = document.getElementsByTagName('script'),
      currentScript = scripts[scripts.length - 1],
      scriptUrl = currentScript;

  alert("scriptUrl: " + scriptUrl);
})();

The above works because at the moment when the script element is being executed, is the last script element of the DOM (scripts[scripts.length - 1]).

Then you have only to make string manipulation on your scriptUrl to extract the GET parameters.

Check an example here, and the external script is here.

CMS
This is working quite well. Thank you!
jfroom