简体   繁体   中英

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 (eg <div id="Hello"></div> , then it would mess up this code)
  2. 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.

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