Javascript在鼠标按下时重写所有外部链接

Javascript to rewrite all external links on mousedown?

本文关键字:外部 链接 重写 鼠标 Javascript      更新时间:2023-09-26

如何使用单个 onmousedown 事件重写所有外部链接

有点像Facebook对它的链接填充程序所做的

请查看有关链接垫片的原始Facebook文章:http://on.fb.me/zYAq0N

要求:

  • 应该适用于 mainsite.com 上的所有子域。

  • 应 example.com 重定向至mainsite.com/link.cgi?u=http://example.com

  • 应仅重定向不属于 mainsite.com 的链接。

使用:

这是为了保护专用 Web 应用程序用户的安全,并保护引荐来源网址。

最好像FB文章中指出的那样,为良好的UI即时执行此操作。

因此,当用户将鼠标悬停在某个链接上时,它会显示正确的链接,但是当他单击它时,js会将其重定向到my.site.com/link.cgi=http://link.com

提前致谢

已解决:https://gist.github.com/2342509

对于单个链接:

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>

因此,要获取所有外部链接:

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"
}}

编辑:
找到了这个答案,得到了一个更好的主意。

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; }
}};

如果你使用 jQuery,那么以下内容将起作用

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

否则

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);
  }
}