繁体   English   中英

Javascript 重写 mousedown 上的所有外部链接?

[英]Javascript to rewrite all external links on mousedown?

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

有点像 facebooks 用它的链接 shim 做的事

请查看原文 Facebook 关于链接 shim 的文章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);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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