简体   繁体   中英

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.

I think I found a solution here: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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