简体   繁体   中英

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.

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.

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.

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

/:\/\//

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

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.

If you have to, you can dynamically create the regular expression from the current domain by checking 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'));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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