Javascript .replace command replace page text?

后端 未结 3 1732
孤独总比滥情好
孤独总比滥情好 2020-11-27 07:54

Can the JavaScript command .replace replace text in any webpage? I want to create a Chrome extension that replaces specific words in any webpage to say something else (examp

3条回答
  •  情歌与酒
    2020-11-27 08:12

    Ok, so the createTreeWalker method is the RIGHT way of doing this and it's a good way. I unfortunately needed to do this to support IE8 which does not support document.createTreeWalker. Sad Ian is sad.

    If you want to do this with a .replace on the page text using a non-standard innerHTML call like a naughty child, you need to be careful because it WILL replace text inside a tag, leading to XSS vulnerabilities and general destruction of your page.

    What you need to do is only replace text OUTSIDE of tag, which I matched with:

    var search_re = new RegExp("(?:>[^<]*)(" + stringToReplace + ")(?:[^>]*<)", "gi");
    

    gross, isn't it. you may want to mitigate any slowness by replacing some results and then sticking the rest in a setTimeout call like so:

    // replace some chunk of stuff, the first section of your page works nicely
    // if you happen to have that organization
    //
    setTimeout(function() { /* replace the rest */ }, 10);
    

    which will return immediately after replacing the first chunk, letting your page continue with its happy life. for your replace calls, you're also going to want to replace large chunks in a temp string

    var tmp = element.innerHTML.replace(search_re, whatever); 
    /* more replace calls, maybe this is in a for loop, i don't know what you're doing */  
    element.innerHTML = tmp;
    

    so as to minimize reflows (when the page recalculates positioning and re-renders everything). for large pages, this can be slow unless you're careful, hence the optimization pointers. again, don't do this unless you absolutely need to. use the createTreeWalker method zetlen has kindly posted above..

提交回复
热议问题