Javascript How To Check If A Url Is Same Origin As Current Page?
Solution 1:
you could parse each link, and then compare the "hostname" component to that returned by window.location.hostname.
;(function(){
"use strict";
var parseUrl = function(link){
var a = document.createElement('a');
a.href = link;
return a;
};
var isSameOrigin = function(url1,url2) {
return (url1.hostname === url2.hostname);
};
var localClick = function(ev){
ev.preventDefault();
alert('you clicked a local link');
};
var currentPage = window.location || window.document.location;
document.addEventListener('DOMContentLoaded',function(){
var els = document.querySelectorAll("a");
for (var i=0;i<els.length;i++) {
var el = els[i];
var othercell = el.parentNode.nextSibling.nextSibling;
var isLocal = isSameOrigin( parseUrl(el.href), currentPage );
othercell.innerHTML = isLocal;
if (isLocal) {
// now bind to the element
el.addEventListener('click',localClick);
}
}
});
})();
th {
text-align: left; background-color: #ddd;
}
<table><tr><th>link</th><th>is same origin?</th></tr><tr><td><ahref="http://varsity.com">Varsity</a></td><td></td></tr><tr><td><ahref="http://google.com">Google</a></td><td></td></tr><tr><td><ahref="http://stacksnippets.net">Stack Snippets</a></td><td></td></tr><tr><td><ahref="http://jsfiddle.net">JS Fiddle</a></td><td></td></tr><tr><td><ahref="http://null.jsbin.com">JS Bin</a></td><td></td></tr></table>
Here is the same code on js bin:
Solution 2:
The Origin definiton from the RFC 6454:
Roughly speaking, two URIs are part of the same origin (i.e., represent the same principal) if they have the same scheme, host, and port.
So we need to compare scheme, host, and port from two URIs, if they are the same, then these two URIs are the same origin.
A working code snippet:
functionisOriginSameAsLocation(url) {
var pageLocation = window.location;
varURL_HOST_PATTERN = /(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/;
var urlMatch = URL_HOST_PATTERN.exec(url) || [];
var urlparts = {
protocol: urlMatch[1] || '',
host: urlMatch[2] || '',
port: urlMatch[3] || ''
};
functiondefaultPort(protocol) {
return {'http:':80, 'https:':443}[protocol];
}
functionportOf(location) {
return location.port || defaultPort(location.protocol||pageLocation.protocol);
}
return !!( (urlparts.protocol && (urlparts.protocol == pageLocation.protocol)) &&
(urlparts.host && (urlparts.host == pageLocation.host)) &&
(urlparts.host && (portOf(urlparts) == portOf(pageLocation)))
);
}
Solution 3:
Here's a simple snippet of jQuery that will only preventDefault()
on events called when clicking a link to an external URL.
The logic for assessing the URL is:
- Skip if local path
- Skip if full URL and the host is the same
I think that will work for a lot of simple use-cases.
$("a").on("click", function(e) {
var hrefURL, pageURL;
hrefURL = newURL(this.href);
pageURL = newURL(window.location);
if (!(href.startsWith("/") || hrefURL.host === pageURL.host)) {
return e.preventDefault();
}
});
Solution 4:
Suppose you have the link for your current page is:
<a href="current.html"id="redirect">HomePage</a>
And you are clicking on a random link:
<a href="random.html"id="rdm">HomePage</a>
Then write a javascript function as:
functioncheck(){
if(document.getElementById("rdm").toString().indexOf("current")<0){
// do something /*If it returns a negative value it means that the link we
clicked does not contain the string 'current'(as our host is
current.html) i.e.the link is not our host link */else{
// do something else
}
Hope it helps.
Solution 5:
while the answer from didxga should be less effort on the client side the answer from code monk brings me to a cleaner solution.
functiondoSomething(url) {
// assuming we are in a function where we want to check the same originvar link = document.createElement('a');
link.href = url;
if (link.host !== location.host) {
alert('url is invalid');
return;
}
// do something...
}
Note that I'm using window.location
with location
. You may want to support browsers where this implementation is not working or have a location variable in a parent scope.
Post a Comment for "Javascript How To Check If A Url Is Same Origin As Current Page?"