Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How do I get the URL of script being called?

Tags:

javascript

I include myscript.js in the file http://site1.com/index.html like this:

<script src=http://site2.com/myscript.js></script> 

Inside "myscript.js", I want to get access to the URL "http://site2.com/myscript.js". I'd like to have something like this:

function getScriptURL() {     // something here     return s }  alert(getScriptURL()); 

Which would alert "http://site2.com/myscript.js" if called from the index.html mentioned above.

like image 337
MikeC8 Avatar asked Jun 04 '10 18:06

MikeC8


People also ask

What is a script URL?

Definition and Usage. The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again.

How do I get the current URL?

Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc.

Which attribute specifies the URL of script file?

The src attribute specifies the URL of the media file to play.


1 Answers

From http://feather.elektrum.org/book/src.html:

var scripts = document.getElementsByTagName('script'); var index = scripts.length - 1; var myScript = scripts[index]; 

The variable myScript now has the script dom element. You can get the src url by using myScript.src.

Note that this needs to execute as part of the initial evaluation of the script. If you want to not pollute the Javascript namespace you can do something like:

var getScriptURL = (function() {     var scripts = document.getElementsByTagName('script');     var index = scripts.length - 1;     var myScript = scripts[index];     return function() { return myScript.src; }; })(); 
like image 198
lambacck Avatar answered Oct 05 '22 10:10

lambacck