簡體   English   中英

如何使用JavaScript更改所有外部鏈接?

[英]How to change all external links with Javascript?

我想使用Javascript替換所有外部鏈接。我只想在每個外部鏈接之前添加“ http://example.com/go= ” ...我該怎么做? 請幫忙..

如果當前的.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM