tags:

views:

232

answers:

3

Is there any recommended solutions when an embedding a script that will make a callback to the originating source but the js resides in a different domain. Sometimes other clients would be in a different domain and I can't rely on getting the document or window location.

Currently, I've been using this but not too happy with this solution.

var host = window.location.hostname;
if(host.indexOf('.devols.') > -1){
  return (('https:' == document.location.protocol) ? 'https://' : 'http://') + host; // return dev or localhost
} else if(host.indexOf('.qaols.') > -1){
  return 'qa environment';        
} else {
  return 'prod environment';
}

Update:

So far I've been playing around with this:

var scriptLocation = '';
var SCRIPT_NAME = 'example.js';
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
  var src = scripts[i].getAttribute('src');
  if(src){
    var index = src.lastIndexOf(SCRIPT_NAME);
    if((index > -1) && (index + SCRIPT_NAME.length == src.length)) {
      scriptLocation=src.slice(0, src.indexOf('/my_script_location/'));
      break;
    }
  }
}
return scriptLocation;

So after the page loads the code cycles thru the script tag array and determines the location so the api can make a callback without having to figure out the urls and etc...

+1  A: 

You'd be better off passing this information from the server and populating it in a JavaScript variable when the page is served.

Diodeus
A: 

What about if you specified a callback URL when you ask for the JS? So in your script tag do something like:

<script type="text/javascript" src="http://foo/bar.js?caller=http://blah"&gt;&lt;/script&gt;
sammich
The reason is because the js file does act like a widget and needs to make a callback to it's originating source.
ishortman
A: 

What you're describing violates the same origin policy, so I don't think it could be accomplished with javascript alone.

TenebrousX