[英]How to change all external links with Javascript?
如果当前的.href
不包含document.domain
则可以迭代document.links
HTMLCollection
并将.href
属性设置为所需的字符串。
Array.from(document.links)
.forEach(link =>
link.href = new RegExp(document.domain).test(link.href)
? link.href : "http://example.com/go=")
以下代码段应该起作用。 它遍历所有<a>
元素,并检查href
包含当前域(我使用RegExp对其进行了测试,但也有一些可行的解决方案)。 如果不是,则添加前缀。
const originReg = new RegExp(location.hostname, 'i'); document.querySelectorAll('a').forEach(a => { if (originReg.test(a.href)) return /* internal link */; a.href = `http://example.com/go?url=${encodeURI(a.href)}`; });
<a href="/bar">Bar</a> <a href="baz">Baz</a> <a href="http://example.com/foo">Foo</a>
document.querySelectorAll('a').forEach((anchor) => {
// make sure we return the relative path, not the absolute
// getAttribute(), not .href
const href = anchor.getAttribute('href');
const str = 'http://example.com/go=';
// if the link is an external link, update
// the href attribute
/:\/\//.test(href) && anchor.setAttribute('href', str + href);
});
这将仅针对外部链接。
document.querySelectorAll('a').forEach((anchor) => {
// make sure we return the relative path, not the absolute
const target = anchor.getAttribute('target');
If ( target === '_blank' ){
const href = anchor.getAttribute('href');
const str = 'http://example.com/go=';
anchor.setAttribute('href', str + href);
}
});
//其中大部分是对@Andy代码的编辑。 我不想对那里的内容进行重大更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.