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:
- there might be Classes or IDs named
Hello
(e.g.<div id="Hello"></div>
, then it would mess up this co开发者_开发问答de) - For some reason Gmail breaks when I try to replace the body
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.
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.
精彩评论