How to change all external links with Javascript?

纵饮孤独 提交于 2019-12-12 04:16:04

问题


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.



来源:https://stackoverflow.com/questions/45268205/how-to-change-all-external-links-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!