3

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.

2 Answers 2

3

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.

0
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.