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?

0

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

If this is a fully qualified URL, then you need domain = src.split('/')[2] instead of [0] to get the domain. See jsFiddle: jsfiddle.net/jfriend00/xH5jn
Good point. Forgot about the protocol.
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.
thanks Ben, i just really hoped there is a quick command already build into the JS but this will do the trick :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.