Question

I have a Javascript library I'm working on. It can be self-hosted or run from another server. The script makes a number of AJAX calls and the preferred method is making POST requests to the same host as the including page. To allow for cross-domain calls it also supports JSONP, but this limits the amount of data that can be sent (~2K to safely accommodate most modern browsers' URL length limits).

Obviously the user including the script knows where they're getting it from and could manually select JSONP as needed, but in the interest of simplifying things, I'd like to detect, within the script itself, whether the script was loaded from the same host as the page including it or not.

I'm able to grab the script element with jQuery but doing a $('script').attr('src') is only returning a relative path (e.g. "/js/my-script.js" not "http://hostname.com/js/my-script.js") even when it's being loaded from a different host.

Is this possible and if so, how would I go about it?

Thanks in advance.

Was it helpful?

Solution

Don't use JSONP, use CORS headers.

But if you really want to do JS check, use var t = $('script')[0].outerHTML.

Effect on my page: [20:43:34.865] "<script src="http://www.google-analytics.com/ga.js" async="" type="text/javascript"></script>"

OTHER TIPS

Checking location.host should do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top