Is there a "safe" way to check if the same origin policy applies to an URL before actually trying to use ajax methods? Here is what I have:
function testSameOrigin(url) {
var loc = window.location,
a = document.createElement('a');
a.href = url;
return a.hostname == loc.hostname &&
a.port == loc.port &&
a.protocol == loc.protocol;
}
This sort of works, but it’s kind of a manual guess based on the wikipedia article. Is there a better way of pre-checking cross domain allowance? jQuery is OK to use.
Interesting question! I searched around and couldn't find anything other than what you posted, but I did come across this when I was messing around with some test code. If you just want a simple way to test a URL without making a request, I'd do it the way you're doing it. If you don't care about making a request to test, you could try this:
Make a simple ajax request to whatever URL you want:
var ajaxRequest = $.ajax({
url: 'http://www.google.com',
async: false
});
which returns a jqXHR
object, which you can then check:
ajaxRequest.isRejected(); // or...
ajaxRequest.isResolved();
Now, the only problem with this is that isRejected()
will evaluate to true
for every single case where the page doesn't load (i.e. 404 Not Found, etc.), but you can check the status code with:
ajaxRequest.status;
It looks like the above line will return 0
when you attempt to break the same origin policy, but it will return the appropriate error code (again, i.e. 404) in other cases.
So to wrap up, maybe you could try doing something like:
function testSameOrigin(testUrl) {
var ajaxRequest = $.ajax({
url: testUrl,
async: false
});
return ajaxRequest.isRejected() && ajaxRequest.status === 0;
}
Not a definitive answer by any means, but I hope it helps you figure out what you're looking for!