brian14708
brian14708

Reputation: 1961

Chrome extension replace text

I want to replace all the text on the page, for example: all "Hello" to "Hi"

I'm currently using

body.innerHTML = body.innerHTML.replace("Hello", "Hi");

I've been running into two problems:

  1. there might be Classes or IDs named Hello (e.g. <div id="Hello"></div>, then it would mess up this code)
  2. For some reason Gmail breaks when I try to replace the body

Upvotes: 3

Views: 2748

Answers (2)

Simon Scarfe
Simon Scarfe

Reputation: 9638

Because this is Chrome-specific and you don't have to worry about legacy browsers (cough IE), this sounds like a job for a treeWalker. There's a decent example of how to use it here.

Upvotes: 4

T.J. Crowder
T.J. Crowder

Reputation: 1075925

Doing that innerHTML thing will trash all the event handlers hooked to elements on the page, because what you're doing there is destroying the previous elements and replacing them with new ones.

To do what you want to do, you'll have to walk the dom and update the values of the text nodes (only). There's an example, with full code and a live copy, in this other answer here on Stack Overflow. You just have to change what the handleText function is doing, and you're good to go.

Upvotes: 1

Related Questions