简体   繁体   English

使用javascript编辑外部链接

[英]Edit external links with javascript

Here's my current code: 这是我当前的代码:

window.onload = function() {
    document.querySelectorAll('a').forEach((anchor) => {
        const href = anchor.getAttribute('href');
        /:\/\//.test(href) && anchor.setAttribute('href', 'http://example.com/go=' + href);
        console.log(anchor.getAttribute('href'));
    });
}

The code is supposed to add http://example.com/go= before all external links. 该代码应该在所有外部链接之前添加http://example.com/go=

If I link to an external page, it is adding it correctly. 如果我链接到外部页面,则说明它已正确添加。 However, it's also adding it to internal pages depending on how I link to them. 但是,它还会根据我链接到内部页面的方式将其添加到内部页面。 If I link to them like <a href="/testing"> it doesn't added it (which is correct. 如果我像<a href="/testing">这样链接到它们,则不会添加它(这是正确的。

But if I link to my website like <a href="http://website.com/testing"> then it's assuming that's an external URL since I included the domain and adding the string before it. 但是,如果我像<a href="http://website.com/testing">那样链接​​到我的网站,则假定这是一个外部URL,因为我包括了域并在该域之前添加了字符串。

What am I doing wrong? 我究竟做错了什么?

You can replace the regular expression you use to test with one that also checks that the href domain does not bein with website.com : change 您可以用一个测试正则表达式替换一个正则表达式,该正则表达式还可以检查href域是否不属于website.com

/:\/\//

to

/:\/\/(?!website\.com)/

You also might consider using an if statement instead of && , to make the code more readable (leave the tricky-looking && -as- if to the minifiers): 您还可以考虑使用if语句而不是&& ,以使代码更具可读性(将棘手的&& -as- if留给压缩程序):

document.querySelectorAll('a').forEach((anchor) => {
  const href = anchor.getAttribute('href');
  if (/:\/\/(?!website\.com)/.test(href)) {
    anchor.setAttribute('href', 'http://example.com/go=' + href);
  }
  console.log(anchor.getAttribute('href'));
});

Also note that querySelectorAll returns a NodeList , not an array, and only newer browsers support NodeList.prototype.forEach - Chrome users on Vista and older systems will run into errors, for example, so if you want to support them, make sure to include a polyfill, if you aren't already. 还要注意, querySelectorAll返回一个NodeList ,而不是一个数组,并且只有较新的浏览器才支持NodeList.prototype.forEach例如,在Vista和较旧系统上的Chrome用户会遇到错误,因此,如果要支持它们,请确保包含一个polyfill(如果还没有的话)。

If you have to, you can dynamically create the regular expression from the current domain by checking window.location.hostname : 如果需要,可以通过检查window.location.hostname从当前域动态创建正则表达式:

document.querySelectorAll('a').forEach((anchor) => {
  const { hostname } = window.location;
  const escapedHostname = hostname.replace(/\./g, '\\.');
  const pattern = new RegExp(`://(?!${escapedHostname})`);
  const href = anchor.getAttribute('href');
  if (pattern.test(href)) {
    anchor.setAttribute('href', 'http://example.com/go=' + href);
  }
  console.log(anchor.getAttribute('href'));
});

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

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