Why does my browser extension do nothing on page load (except in the toolbox)?

124 Views Asked by At

I've been trying to make a Firefox extension. I've had success with doing stuff after a user interaction (like a browser action). But I want my extension to do something without user interaction. But no matter what I do, I can't get anything to happen on page load. Here is my super reduced code:

manifest.json

{
  "name": "Test",
  "version": "0.1",
  "manifest_version": 2,
  "background": {
    "scripts": ["test.js"]
  }
}

test.js

document.addEventListener("DOMContentLoaded", init);

function init() {
  document.body.innerHTML = "Hello world!";
}

What am I doing wrong here? It works in the toolbox, just not anywhere else!

I've also tried adding host permissons like this:

"permissions": [
    "*://*.facebook.com/*"
  ],
1

There are 1 best solutions below

2
On BEST ANSWER

Try this:

manifest.json

{
  "name": "Test",
  "version": "0.1",
  "manifest_version": 2,
  "background": {
    "scripts": ["background.js"]
  },
  "permissions": ["webNavigation", "*://*.facebook.com/*"]
}

background.js

browser.webNavigation.onDOMContentLoaded.addListener(handleOnDOMContentLoaded, {
  url: [{ hostEquals: 'www.facebook.com' }],
});

function handleOnDOMContentLoaded({ tabId }) {
  browser.tabs.executeScript(tabId, { file: 'test.js' });
}

test.js

document.body.innerHTML = 'Hello world!';