Skip to content

Instantly share code, notes, and snippets.

@phloe
Created January 9, 2012 14:17
Show Gist options
  • Select an option

  • Save phloe/1583118 to your computer and use it in GitHub Desktop.

Select an option

Save phloe/1583118 to your computer and use it in GitHub Desktop.
Crossdomain url test
/*
document.location of the current page tested against a url (string) like:
"pages/page.html" // false
"../pages/page.html" // false
"/pages/page.html" // false
"//foo.bar.com/pages/page.html" // false
"http://foo.bar.com/pages/page.html" // false
"//bar.com/pages/page.html" // true
"https://bar.com/pages/page.html" // true
*/
function isXDomain (url) {
return !(
url.match(/^((\.\.\/)|([^:/]+\/)|(\/[^/]))/) ||
(url.match(/^\/\//) || url.indexOf(location.protocol) == 0) &&
url.indexOf("//" + location.hostname) > -1
)
}
@dperini
Copy link

dperini commented Jan 10, 2012

This is what I have come up with:

function isXDomain(dURL, sURL) {
  var HOSTNAME = /^(?:https?:)?(?:\/\/)?([^\/]+)\//;
  sURL || (sURL = location.href.match(HOSTNAME));
  dURL && (dURL = (dURL + '').match(HOSTNAME));
  return sURL && !!dURL && sURL[1] === dURL[1];
}

the second parameter is optional, if one wants to compare against a secondary URL instead of the current "location.href".

The above code also accepts the following as valid URL:

bar.com/pages/page.html

not much shorter though.

@phloe
Copy link
Author

phloe commented Jan 10, 2012

..but shorter nevertheless :D

The added secondary URL is nice (especially considering the shortness).

But should "bar.com/pages/page.html" be considered a valid URL considering a <a href="bar.com/pages/page.html">My page</a> on "foo.com/index.html" would point to "foo.com/bar.com/pages/page.html"?? Depends on the strictness I guess...

@dperini
Copy link

dperini commented Jan 10, 2012

Haven't checked about the validity of that URL, however try changing the RE to:

var HOSTNAME = /\/\/([^\/]+)\//;

to avoid that dubious condition and see if it fits exactly all your tests/needs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment