Getting the URL of a JavaScript executable (mostly a problem with IE6-7)

Hi everyone, I tried to build a generic function that retrieves the absolute URL of a JavaScript executable on a web page:

http://gist.github.com/433486

Basically you call something like this:

getScriptName(function(url) { console.log(url); // http://www.example.com/myExternalJsFile.js }); 

inside an external JavaScript file on the page and then can do something with it (for example, find the <script> tag that loaded it, for example).

It works great in almost all the browsers I tested (Firefox, Chrome, Safari, Opera v10 at least and IE 8).

In IE 6 and 7, it does not seem to work. The callback function is executed, but the resulting name is the URL of the main HTML page, not a JavaScript file. Continuing the example, getScriptName calls the callback with the parameter: http://www.example.com/index.html

So, all I'm really asking about is there another way to get the URL of the current JavaScript file (which could be a specific IE 6 and 7 hacker)? Thanks in advance!

EDIT: Also, this will not work in every case, so please do not recommend:

 var scripts = document.getElementsByTagName("script"); return scripts[scripts.length-1].src; 

I would like it to work in the case of dynamically created script tags (possibly not placed last on the page), as well as lazy-loading.

+19
javascript html cross-browser internet-explorer absolute
Jun 10 '10 at 10:50
source share
2 answers

A lot depends on what you have access to. If, as it seems, you are trying to do this completely in JS code, I do not think that you can do this for some of the reasons shown above. Perhaps you could get 90% of the way, but not be final.

If you work in a dotnet environment (which is the only one I know), I would suggest using a module that will intercept all JS requests and add the request location to them or something like that.

I think you need to access this from the server side, not from the client side. I do not think you will have a definitive answer on the client side. I think you will also try to get a response from the server, but you may be more successful.

+1
Jul 04 2018-11-11T00:
source share

Sorry, I suspect you can fight this. IE earlier than version 8 usually displays error messages from javascript form errors:

 line: 342 char: 3 error: expected identifier, string or number code: 0 url: http://example.com/path/to/resource 

where url is window.location.href, not the URL of the external Javascript resource that contains this problem. I believe IE gives a useless url value, as the script url is not accessible to IE at this point, and none of them are available for any Javascript you could write to try to display it.

I would like to be able to refer to IE8 release notes that say this bug / feature has been fixed, so the reason I created this as a wiki community. My MSDN foo is pretty weak!

+1
Jul 04 '11 at 16:19
source share



All Articles