Skip to content
Advertisement

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!

JavaScript

Updated test webpage:

JavaScript

Updated manifest file:

JavaScript

Updated main script testing both answers:

JavaScript

Advertisement

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:

JavaScript

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement