How to change all external links with Javascript?

2019-09-16 10:52发布

问题:

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? Please help..

回答1:

You can iterate document.links HTMLCollection and set .href property to the required string if the current .href does not include document.domain

Array.from(document.links)
.forEach(link => 
  link.href = new RegExp(document.domain).test(link.href)
              ? link.href : "http://example.com/go=")


回答2:

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). 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>



回答3:

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



回答4:

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. I did not want to make major changes to what was there.