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.
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.
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.
The src attribute specifies the URL of the media file to play.
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; }; })();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With