[英]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.