views:

29

answers:

1

Here's 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?

+1  A: 

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"&gt;
     </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.

Pekka