开发者

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 variabl开发者_开发技巧e 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜