简体   繁体   English

用Javascript替换所有外部链接

[英]Javascript to replace all external links

What I am trying to achieve is replacing all external links when page is loaded. 我要实现的目标是在加载页面时替换所有外部链接。

As an example, the original url: 例如,原始网址:

http://microsoft.com/faq become newurl

should be changed to: 应该更改为:

http://redirect.com/?url=http://microsoft.com/faq 

I tried different solutions I found with Google, but nothing seems to work for me. 我尝试了与Google一起找到的其他解决方案,但似乎没有任何效果。

I think I found a solution here: http://jsfiddle.net/eK7XW/ 我想我在这里找到了解决方案: http : //jsfiddle.net/eK7XW/

Edited to check internal domain: 编辑以检查内部域:

function isExternal(link, domain) {
    var re = /http(s?):\/\/([\w]+\.){1}([\w]+\.?)+/;
    return re.exec(link)[0] === domain;
}

var SITE = "http://redirect.com/?url=";
var INTERNAL_DOMAIN = "http://www.yourdomain.com";
var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
    if (isExternal(links[i].href), INTERNAL_DOMAIN) {
        links[i].href = SITE + links[i].href;
    }
}

If you need to check for subdomains or to not specify the internal domain, I believe the code is easy to adapt. 如果您需要检查子域或不指定内部域,我相信代码很容易适应。

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

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