0

I have a content script (running in world MAIN) that is listening to changes in console.log and it should send a message to background.ts when a console.log happens.

manifest.json

{
"content_scripts": [
    {
      "world": "MAIN",
      "js": ["src/contentScripts/registerConsoleLogs.ts"],
      "matches": [
          "http://*/*",
          "https://*/*"
      ],
      "run_at": "document_start"
    }
  ],
}

registerConsoleLogs.ts

console.stdlog = console.log.bind(console)

console.log = function () {
  console.stdlog.apply(console, arguments)

  const payload = {
    name: 'registerLog',
    payload: { severity: 'warning', log: arguments }
  }
}

export default {}

background.ts

browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.name === 'registerLog') {
    console.log('log received: ')
    console.log(request.payload)
  }
})

My doubt is: how can I send a message from registerConsoLogs.ts to background.ts?

The examples (1, 2) do not use the world: "MAIN". I'm fairly new to developing web extension and would love some guidance on how to pass the messages from content script with world: "MAIN" to background

Bruno Francisco
  • 3,841
  • 4
  • 31
  • 61
  • 1
    A `MAIN` world script is just a web page script, it has no access to any of the extension's API by default, so you'll need to use CustomEvent messaging with a second content script without `world`, which will forward the message into the extension. There should be examples for ManifestV2 (basically same as MV3) around for using messaging e.g. [Can a site invoke a browser extension?](https://stackoverflow.com/a/10527809) (note that your MAIN world script is the *"injected script"* in MV2). – wOxxOm Jun 20 '23 at 15:07

0 Answers0