Modify page from background script?

Is it possible to modify the page (e.g., add a DIV to the BODY) from a background script? Things like document.body.appendChild(…); don’t seem to work.

Or do I have to create a content script and send a message from the background script to the content script?

The fine documentation doesn’t explain this.

Background script is running in its own special invisible page so DOM operations will not be visible.

For modifying page you can use the Content script (as you mentioned), which is useful if you need to modify the page every time you visit it.

Otherwise you can use browser.tabs.executeScript to execute file (or code) in the tab:

Also see this article regarding the overall anatomy of extensions:

1 Like

One of my extensions uses that technique of injecting changes from the background script (for keyboard shortcuts) or popup script (for the UI) using executeScript. In case an example could be helpful: