Skip to content

How to replace specific links in a webpage using Javascript

I am trying to make a chrome extension script that scans a webpage for specific clickable links, and replaces them with other links if they match.

Here is what I have since updating this post with a minimum reproducible example (updated farther below) but it only works for function rewritePage1 which is based on the answer I received specifying outerHTML. Thank you!

 var matcher = "alias text"
      var newText = "true text";
      function replaceText(selector, text, newText, flags) {
      //var matcher = new RegExp(text, flags);
      var elems = document.querySelectorAll(selector), i;
    
      for (i = 0; i < elems.length; i++)
        if (!elems[i].childNodes.length)
          elems[i].innerHTML = elems[i].innerHTML.replace(matcher, newText);
    }

Updated test webpage:

    <html>
    <h1>test webpage</h1>
    <p>alias text</p>
    <a href="https://yahoo.com">alias test 1</a>
    <p><a href="https://bing.com">alias test 2</a></p>
    </html>
    

Updated manifest file:

 {
      "name": "OzWizard3",
      "action": {},
      "manifest_version": 3,
      "version": "0.1",
      "description": "demo to replace specific urls on a webpage.",
      "permissions": [
    "activeTab",
    "scripting",
    "clipboardRead",
    "clipboardWrite"
  ],
  "background": {
    "service_worker": "ozwizard3.js"
  }
}

Updated main script testing both answers:

//chrome extension runs when activated by clicking extension icon.
//lookup a url in a database or dictionary as key.
//If found a match on the page, replace it with the value of that key.

function rewritePage1() {
let urlLinksToChange = 'https://yahoo.com';
let replaceWithThisElement = `<a href="https://google.com" style="color:red">Replaced!</a>`;
let linksToChange = document.querySelectorAll(`a[href*="${urlLinksToChange}"]`)
linksToChange.forEach(l => {
     l.outerHTML = replaceWithThisElement;
});
}

function rewritePage2(){
  var matcher = "https://bing.com"
  var newText = "https://yahoo.com";

  function replaceText(text, newText) {
      // get all links with specific urls
      var links = document.querySelectorAll(`a[href*="${text}"]`);
      // loop through all links
      for (var i = 0; i < links.length; i++) {
          // get the href
          var href = links[i].getAttribute('href');
          // replace the href
          links[i].setAttribute('href', newText);
      }
  }
}

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: rewritePage1
  });
});

Answer

If you want to replace whole elements, not just its URLs, then for that, we can use outerHTML.

For example if we want to replace all links that start with https://meta. and replace with <a href="https://google.com" style="color:red">Replaced!</a>. We would do this:

let urlLinksToChange = 'https://meta.';
let replaceWithThisElement = `<a href="https://google.com" style="color:red">Replaced!</a>`;
let linksToChange = document.querySelectorAll(`a[href*="${urlLinksToChange}"]`)
linksToChange.forEach(l => { 
     l.outerHTML = replaceWithThisElement;
});

The difference between innerHTML vs outerHTML is that innerHTML modifies the internals of the node, while outerHTML modifies the whole node itself.

https://ravisah.in/blog/what-is-the-difference-between-innerhtml-and-outerhtml Source: https://ravisah.in/blog/what-is-the-difference-between-innerhtml-and-outerhtml