[英]Edit external links with javascript
這是我當前的代碼:
window.onload = function() {
document.querySelectorAll('a').forEach((anchor) => {
const href = anchor.getAttribute('href');
/:\/\//.test(href) && anchor.setAttribute('href', 'http://example.com/go=' + href);
console.log(anchor.getAttribute('href'));
});
}
該代碼應該在所有外部鏈接之前添加http://example.com/go=
。
如果我鏈接到外部頁面,則說明它已正確添加。 但是,它還會根據我鏈接到內部頁面的方式將其添加到內部頁面。 如果我像<a href="/testing">
這樣鏈接到它們,則不會添加它(這是正確的。
但是,如果我像<a href="http://website.com/testing">
那樣鏈接到我的網站,則假定這是一個外部URL,因為我包括了域並在該域之前添加了字符串。
我究竟做錯了什么?
您可以用一個測試正則表達式替換一個正則表達式,該正則表達式還可以檢查href
域是否不屬於website.com
:
/:\/\//
至
/:\/\/(?!website\.com)/
您還可以考慮使用if
語句而不是&&
,以使代碼更具可讀性(將棘手的&&
-as- if
留給壓縮程序):
document.querySelectorAll('a').forEach((anchor) => {
const href = anchor.getAttribute('href');
if (/:\/\/(?!website\.com)/.test(href)) {
anchor.setAttribute('href', 'http://example.com/go=' + href);
}
console.log(anchor.getAttribute('href'));
});
還要注意, querySelectorAll
返回一個NodeList
,而不是一個數組,並且只有較新的瀏覽器才支持NodeList.prototype.forEach
例如,在Vista和較舊系統上的Chrome用戶會遇到錯誤,因此,如果要支持它們,請確保包含一個polyfill(如果還沒有的話)。
如果需要,可以通過檢查window.location.hostname
從當前域動態創建正則表達式:
document.querySelectorAll('a').forEach((anchor) => {
const { hostname } = window.location;
const escapedHostname = hostname.replace(/\./g, '\\.');
const pattern = new RegExp(`://(?!${escapedHostname})`);
const href = anchor.getAttribute('href');
if (pattern.test(href)) {
anchor.setAttribute('href', 'http://example.com/go=' + href);
}
console.log(anchor.getAttribute('href'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.