Created
January 9, 2012 14:17
-
-
Save phloe/1583118 to your computer and use it in GitHub Desktop.
Crossdomain url test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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 | |
| ) | |
| } |
Author
..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...
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
This is what I have come up with:
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:
not much shorter though.