开发者

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 co开发者_开发问答de)
  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜