Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  199] [ 6]  / answers: 1 / hits: 26675  / 15 Years ago, fri, june 12, 2009, 12:00:00

Is there a simple and reliable way to determine the URL of the currently-executing JavaScript file (inside a web page)?



My only thought on this is to scan the DOM for all the script src attributes to find how the current file was referenced and then figure out the absolute URL by applying it to document.location. Anyone have other ideas, is there some super-easy method I completely overlooked?



UPDATE: Script elements accessed via the DOM already have a src property which contains the full URL. I don't know how ubiquitous/standard that is, but alternatively you can use getAttribute(src) which will return whatever raw attribute value is in the [X]HTML.


More From » dom

 Answers
17

Put this in the js file that needs to know it's own url.



Fully Qualified (eg http://www.example.com/js/main.js):



var scriptSource = (function(scripts) {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];

if (script.getAttribute.length !== undefined) {
return script.src
}

return script.getAttribute('src', -1)
}());


Or
As it appears in source (eg /js/main.js):



var scriptSource = (function() {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];

if (script.getAttribute.length !== undefined) {
return script.getAttribute('src')
}

return script.getAttribute('src', 2)
}());


See http://www.glennjones.net/Post/809/getAttributehrefbug.htm for explanation of the getAttribute parameter being used (it's an IE bug).


[#99331] Sunday, June 7, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelynkarsynr

Total Points: 472
Total Questions: 98
Total Answers: 96

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
jocelynkarsynr questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, May 10, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
;