Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract external javascript query string/anchor value: file.js#foo=bar

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.

like image 238
jfroom Avatar asked May 14 '26 02:05

jfroom


2 Answers

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.

like image 111
Christian C. Salvadó Avatar answered May 15 '26 15:05

Christian C. Salvadó


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.

like image 30
Guffa Avatar answered May 15 '26 17:05

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!