0

I have an external JavaScript file that is stored at: http://example.com/script.js. I'd like to extract out http://example.com from inside the JavaScript file. The only problem is that I'm embedding the JavaScript file in a website with a different domain. I've looked into using window.location but that will return the url of the page that has embedded the JavaScript instead of the url that's hosting the script.

example.com/script.js

var hostingUrl = window.location.origin;
alert(hostingUrl);

anotherdomain.com

<!-- This will alert: 'anotherdomain.com' instead of: 'example.com' -->
<script src="http://example.com/script.js"></script>
Dehli
  • 5,950
  • 5
  • 29
  • 44
  • 1
    `alert(document.currentScript.src)` for older browsers, and not using `async` or `defer` attribs on the – dandavis Sep 15 '15 at 17:09
  • Heads up, document.currentScript is not supported in IE. https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript – SacWebDeveloper Sep 15 '15 at 17:11
  • 1
    can you control the `script src...` code? Then you could use ` – tillz Sep 15 '15 at 17:12
  • @tillz: that won't work with `require()`-type solutions, but should work otherwise. – dandavis Sep 15 '15 at 17:13
  • 1
    @tillz I had thought about doing something like that but I was curious if there was a way to do it completely from within the JavaScript file. Thanks @dandavis & @SavWebDeveloper. `document.currentScript` would be perfect in a no-IE world :( – Dehli Sep 15 '15 at 17:15
  • check that out. apparently you can't do that http://stackoverflow.com/a/14161737/4810628 – user786 Sep 15 '15 at 17:18

0 Answers0