繁体   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