开发者

Accessing the location object of an external script from the external script

开发者 https://www.devze.com 2023-01-02 02:51 出处:网络
Here\'s开发者_StackOverflow中文版 an interesting JS q... suppose you have: host1.html on host1.com which references an external javascript (host2.js) on host2.com.In the host2.js, I\'d like to get th

Here's开发者_StackOverflow中文版 an interesting JS q... suppose you have:

host1.html on host1.com which references an external javascript (host2.js) on host2.com. In the host2.js, I'd like to get the location.hostname of the host serving the host2.js, but because host2.js is called inside of host1.html, it returns the location.hostname of host1.

Is there a way to get the location object of the external script within the external script being called?


I think similar questions have been asked before, and the answer was always no, this can't be done.

Workarounds:

  • Work through the parent document's script elements and, using a counter variable, find out which one we're in (ugh)

  • Output the current URL into the included script on server side, e.g. in PHP: script_current_url = <?php echo "http://".$_SERVER["HTTP_HOST"]."/".$_SERVER["REQUEST_URI"] (there's a variable for the protocol part too, I just forgot the name)

  • Set a variable before each <script> tag:

     <script type="text/javascript">
     script_current_url = "http://www.example.com/include.js";
     </script>
    
     <script type="text/javascript" src="http://www.example.com/include.js">
     </script>
    

    this is kludgy, but could be simplified by building a JS function that includes the file and sets the right variable automatically.

I like the server-side approach the best, but depending on your platform, it has other implications like having to send all .js resources through a resource-expensive interpreter.

0

精彩评论

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

关注公众号