简体   繁体   中英

Javascript to rewrite all external links on mousedown?

How can i rewrite all external links with a single onmousedown event?

Kinda like what facebooks does with it's link shim

Please check the original Facebook Article about the link shim : http://on.fb.me/zYAq0N

Requirements:

  • Should work for all subdomains on mainsite.com.

  • Should redirect example.com to mainsite.com/link.cgi?u=http://example.com

  • Should only redirect links not belonging to mainsite.com.

Uses:

This is for security of the users of a private web app, and to protect referrers.

Best to do it on the fly for good UI as pointed out in the FB article.

That's so when users hovers over some link it shows the correct link but when he clicks it, js redirects it to my.site.com/link.cgi=http://link.com

Thanks in advance

SOLVED : https://gist.github.com/2342509

For an individual link:

function $(id){ return document.getElementById(id); }
$(link).onclick = function(){ this.href = "http://otherlink.com"; }

<a href="http://example.com" id="link">My Sheisty Link</a>

So to get all external links:

window.onload = function(){
var links = document.getElementsByTagName("a");
for(a in links){
  var thisLink = links[a].href.split("/")[2];
  if(thisLink !=== window.location.hostname){
    links[a].href = "http://mainsite.com/link.cgi?u=" + links[a]; }
  // Or you could set onclick like the example above
  // May need to accommodate "www"
}}

Edit:
Found this answer and got a better idea.

document.onclick = function (e) {
 e = e ||  window.event;
 var element = e.target || e.srcElement;

if (element.tagName == 'A') {
 var link = element.href.split("/")[2];
  if(link !=== window.location.hostname){
    links[a].href = "http://mainsite.com/link.cgi?u=" + links[a]; }
    return false; // prevent default action and stop event propagation
  }else{ return true; }
}};

If you use jQuery then the following will work

$('a:link').mousedown(function() { 
  this.href = 'http://my.site.com/link.cgi=' + this.href; 
});

Otherwise

var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
  var a = anchors[i];
  if(a.href) {
    a.addEventListener('mousedown', function(e) {
      this.href = 'http://my.site.com/link.cgi=' + this.href;
    }, false);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM