Another way to approach this is with event delegation. This method rewrites the URL at the point the link is used (and not before):
window.onload = function(){
var de = document.documentElement || document.body;
/// an event listener that steps in at the point the user has
/// clicked any element on the page. We specifically detect for
/// links and redirect the outcome
var proxyLink = function(e,t,href){
/// handle old versions of IE
e = e || Event; t = e.target || e.srcElement;
/// hashs can occur at the end of external links, so am only checking
/// your specific case. Switched to using getAttribute so as to get
/// the original href string.
if ( t.getAttribute('href').charAt(0) === '#' ) return;
if ( t.getAttribute('href').indexOf('../') === 0 ) return;
if ( String(t.nodeName).toLowerCase() == 'a' ) {
if ( e.preventDefault ) { e.preventDefault(); }
href = makeHrefAbsoluteIfPossible(t.href);
window.location = 'http://this.com/?url='+encodeURIComponent(href);
return (e.returnValue = false);
}
}
/// add the listener to the body or document element, this will trigger
/// the event onclick thanks to event bubbling.
if ( de.addEventListener ) {
/// handles modern browsers
de.addEventListener('click', proxyLink, true);
}
else {
/// handles old IE
de.attachEvent('onclick', proxyLink)
}
}
I've also create the following function to extend your hrefs to their absolute value based upon the current window.location
. I'm never sure which browsers will return an absolute URL or the original href text, so this function is just incase the latter happens:
function makeHrefAbsoluteIfPossible( href ){
var path;
if ( href.indexOf(':') == -1 ) {
if ( href.charAt(0) == '/' ) {
path = href;
}
else {
path = String(window.location.pathname);
if ( path.indexOf('/') != -1 ) {
path = path.substring(0,path.lastIndexOf('/')) + '/';
}
path += href;
}
return window.location.protocol +'://' +
window.location.host + path;
}
return href;
}
Working example (with an alert instead of a redirect):
http://jsfiddle.net/teykz/2/
The benefits to this method are that it will work with applications that generate new html content during runtime... this most often happens with AJAX powered systems. Plus the links still appear as the original to the user (this can be desired depending on what you are doing).