[英]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
提前致謝
對於單個鏈接:
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.