Sharon Haim Pour
Sharon Haim Pour

Reputation: 6713

Can JavaScript access it's own source url?

Suppose I'm embedding a javascript in HTML page:

<script type="text/javascript" src="www.mydomain.com/script.js?var1=abc&var2=def"></script> 

Is there a way I can get the src url inside the script and extract the params?

Upvotes: 1

Views: 1478

Answers (4)

dandavis
dandavis

Reputation: 16726

this little hack uses error handling to find the location of external scripts from within:

(function(){ // script filename setter, leaves window.__filename set with active script URL.
if(self.attachEvent){
 function fn(e,u){self.__filename=u;}
 attachEvent("onerror",fn);
 setTimeout(function(){detachEvent("onerror", fn)},20);
 eval("gehjkrgh3489c()");
}else{
 Object.defineProperty( window, "__filename", { configurable: true, get:function __filename(){
   try{document.s0m3741ng()}catch(y){
    return "http://" + 
     String(y.fileName || y.file || y.stack || y + '')
     .split(/:\d+:\d+/)[0].split("http://")[1];
    } 
 }})//end __filename
}//end if old IE?
}());

it sets a global "__filename" property when run, so atop an external script, the __filename is in effect for the execution of the whole script.

i strongly prefer to sniff url parts from scr attributes, but this works in most browsers and without knowing the URL ahead of time.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707736

Here are two other solutions that will work no matter how the script is loaded (even if they are loaded dynamically or with async or defer attributes):

Put an id on the script tag.

<script id="myscript" type="text/javascript" src="www.mydomain.com/script.js?var1=abc&var2=def"></script>

Then, you can find it with the id:

$("#myscript").attr("src")

Or second, if you know the filename, you can search for any script tag that contains that filename:

function findScriptTagByFilename(fname) {
    $("script").each(function() {
        if (this.src.indexOf(fname) !== -1) {
            return this.src;
        }
    });
}

var url = findScriptTagByFilename("/script.js");

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116140

I don't think there is a property already inside the script that points to this url.

From the script, you can read the DOM. So you can lookup the script tag and inspect its src attribute, but if you got multiple scripts (or the DOM was modified), you cannot really know for sure which one it is.

I assume it is for checking input. So to solve this, you can eiter:

  • Render the script through a server side script (PHP), and let it output variables. Disadvantage: eats more server resources and makes caching a bitch.
  • Just get parameter from all the scripts loading from your domain. Maybe it doesn't matter much, or you have only one script anyway. Disadvantage: In this case this is possible, but not very reliable and resistant to changes.
  • My preferred: Add the variables to the script tag (actually, to another script tag) to make them available directly in Javascript, rather than parsing the script url.

Like this:

<script type="text/javascript">
  var1 = 'abc';
  var2 = 'def';
</script>
<script type="text/javascript" src="www.mydomain.com/script.js"></script>

Upvotes: 0

Quentin
Quentin

Reputation: 944021

Given that you are using a regular script element in the HTML source, you can just get the last script element in the document. Since script elements are (in the absence of attributes that you aren't using in your example) blocking, no more will be added to the document until this one has been executed.

var scripts = document.getElementsByTagName('script');
var last_script = scripts[scripts.length - 1];
var url = script.src;

This won't work if you dynamically add a script element before the last script using DOM.

Upvotes: 5

Related Questions