简体   繁体   English

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

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

I want to replace all my external links using Javascript.. I just want to add " http://example.com/go= " before every external links... How will I do that? 我想使用Javascript替换所有外部链接。我只想在每个外部链接之前添加“ http://example.com/go= ” ...我该怎么做? Please help.. 请帮忙..

You can iterate document.links HTMLCollection and set .href property to the required string if the current .href does not include document.domain 如果当前的.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=")

The following snippet should work. 以下代码段应该起作用。 It iterates over all <a> elements and checks if the href contains the current domain (I test it using an RegExp, but there's also solutions thinkable as well). 它遍历所有<a>元素,并检查href包含当前域(我使用RegExp对其进行了测试,但也有一些可行的解决方案)。 If not, the prefix is added. 如果不是,则添加前缀。

 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);
});

Example

This will only target external links. 这将仅针对外部链接。

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);
  }
});

// most of this was an edit to @Andy code. //其中大部分是对@Andy代码的编辑。 I did not want to make major changes to what was there. 我不想对那里的内容进行重大更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM