0

Here's a simplified version of what I want to do.

I have this in my manifest:

"content_scripts": [
  {
    "matches": ["*://*.foo.com/*"],
    "js": [ "content.js"]
  }
]

And I have a file in my extension called stuff.html.

When a user visits a foo.com page, I want to inject some html into certain areas of the page. I want to maintain this html in a separate file. So I want to do something like this in content.js:

stuff = readfile("stuff.html")

document.body.innerHTML = document.body.innerHTML.replace('bad stuff', stuff);

"readfile" of course is a fake method I made up for the question.

How can I do this?

John Bachir
  • 22,495
  • 29
  • 154
  • 227
  • Do not, under any circumstance, use some outer `innerHTML` to replace things. You will completely clobber any and all event listeners in the page, since you're discarding the HTML completely and rebuilding it from text representation only. – Xan Mar 22 '16 at 15:22
  • What's wrong with that? – John Bachir Mar 23 '16 at 14:45
  • I did explain already - basically, you're destrying all internal DOM nodes, converting them to text (which loses stuff like event listeners attached) and then recreate using only that text. Most JavaScript present on the page will break. If you want to operate on text, only modify text nodes. If you want to replace DOM nodes, use jQuery or vanilla DOM manipulation to replace. – Xan Mar 23 '16 at 14:47
  • My example is `document.body.innerHTML=` -- clearly my intention is indeed to destroy all DOM nodes. – John Bachir Mar 23 '16 at 14:52
  • If your intention is to make the entire page non-functional, _go right ahead_. – Xan Mar 23 '16 at 14:53

0 Answers0