0

I was making a simple extension for Chrome to replace the first occurrence of string that I find in the body tag. I placed the following code inside content.js:

document.body.innerHTML = document.body.innerHTML.replace('Hello', 'Hi');

The issue is that there is a noticeable delay when original HTML is visible before the string is replaced. It is especially bad on larger web pages. Is there a way to execute it earlier that won't cause an error of body being null?

miyagisan
  • 805
  • 1
  • 9
  • 19
  • 1) Don't replace in innerHTML - it kills all javascript event listeners. 2) Declare your content script with "run_at": "document_start", 3) Run MutationObserver on `document`, enumerate the mutations and use TreeWalker API to enumerate the text nodes inside each mutation's added nodes, and replace the text inside those text nodes ([example](https://stackoverflow.com/a/39334319)). – wOxxOm Oct 30 '18 at 04:58

1 Answers1

-2

First of all, javascript is client sided. So you should expect that the page will load first (or the required DOM contents) before it looks for Hello inside the DOM.

Second, you are working for a browser extension, so you should expect that the triggers run externally.

For you to get it:

This one would be faster since you load it within the page:

<p>Lorem Ipsum.</p>

<script>
document.body.innerHTML = document.body.innerHTML.replace('Lorem', 'Hi');
</script>