简体   繁体   English

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

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

How can i rewrite all external links with a single onmousedown event?我如何使用单个 onmousedown 事件重写所有外部链接

Kinda like what facebooks does with it's link shim有点像 facebooks 用它的链接 shim 做的事

Please check the original Facebook Article about the link shim : http://on.fb.me/zYAq0N请查看原文 Facebook 关于链接 shim 的文章http://on.fb.me/zYAq0N

Requirements:要求:

  • Should work for all subdomains on mainsite.com.应该适用于 mainsite.com 上的所有子域。

  • Should redirect example.com to mainsite.com/link.cgi?u=http://example.com应该将 example.com 重定向到 mainsite.com/link.cgi?u=http://example.com

  • Should only redirect links not belonging to mainsite.com.应该只重定向不属于 mainsite.com 的链接。

Uses:用途:

This is for security of the users of a private web app, and to protect referrers.这是为了保护私人 web 应用程序用户的安全,并保护推荐人。

Best to do it on the fly for good UI as pointed out in the FB article.正如 FB 文章中指出的那样,最好即时执行此操作以获得良好的 UI。

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就是这样,当用户将鼠标悬停在某个链接上时,它会显示正确的链接,但是当他单击它时,js 会将其重定向到 my.site.com/link.cgi=http://link.com

Thanks in advance提前致谢

SOLVED : https://gist.github.com/2342509解决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如果您使用 jQuery 那么以下将起作用

$('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);
  }
}

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

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