0

Possible Duplicate:
How to get the location (src) of a javascript file?

I have a JavaScript that will be included on third party sites, using <script src="" >. It will be potentially hosted on couple of different domains/hosts of mine. I need to get a domain name of the server that hosts the script, not the domain name of the server that included the script file. So if i host the script file on ABC.COM and it gets included from ZYX.COM i need to retrieve ABC.COM. I could hard-code the domain name inside the script but i rather keep a single version of my code.

Is there a way to do this from within JavaScript?

Community
  • 1
  • 1
android-developer
  • 1,574
  • 4
  • 20
  • 27

1 Answers1

1

Your best choice would be to generate the script file dynamically based on the host it was running on. If that's not an option, you could parse through the DOM and find the script tag that has the right src property, and then parse out the domain name. Of course, it would be tough if a script with the same name from a different origin domain was also included on the page. Otherwise, there is no way for a file to know the URL from which it was referenced.

var scripts = document.getElementsByTagName('script');
var src, i, domain;

for (i=0; i<scripts.length; i++) {
    src = scripts[i].src;

    if (src.indexOf('myFile.js') != -1) {
        domain = src.replace(/^https?\:\/\//i, '').split('/')[0];
        break;
    }
}
Ben Taber
  • 6,426
  • 1
  • 22
  • 17
  • If this is a fully qualified URL, then you need domain = src.split('/')[2] instead of [0] to get the domain. See jsFiddle: http://jsfiddle.net/jfriend00/xH5jn/ – jfriend00 Jul 20 '11 at 01:22
  • Good point. Forgot about the protocol. – Ben Taber Jul 20 '11 at 02:27
  • Added regex to remove http(s):// so it will catch cases with and without the protocol specified. It seems almost all browsers specify the full URL anyway, so that may be unnecessary. – Ben Taber Jul 20 '11 at 02:33
  • thanks Ben, i just really hoped there is a quick command already build into the JS but this will do the trick :) – android-developer Jul 20 '11 at 03:22