Search code examples
google-chromegoogle-chrome-extensionextension-methods

Sending messages between two chrome background scripts


I have 2 background scripts one is background.js and other one is background.ts when I build everything inside build file it looks something like this: /build |-background.js |-helper |--background.ts

What I want to achieve is that I want to send chrome message from .js to .ts background - is that communication possible at all? Both of background are working and everything is great except lack of communication between them.

I have tried to send message from background.js to content script and then to background.ts and it seems that is working but content script is depending on tabs, and I would like to have direct communication channel between background scripts.


Solution

  • There is always only one background context, even if you put multiple script files there, they are all executed in same context. Same as you can put multiple tags on page and they will be all executed in same context. So you don't need any communications API (like chrome.runtime.sendMessage) to exchange data between scripts. How exactly you exchange data between scripts will depend on your project or/and goal, but it's really more like two building bricks of one background script rather than two separate entities

    If you want to run some function from background.ts file when you get WS message, you could just import than function into background.js file and call in WS message handler.

    To do this you'll need to add export keyword to function definition in background.ts:

    export const funcName = () => {...}
    // Or
    export function funcName() {...}
    

    And then import it in background.js and use as normal function:

    import {funcName} from './path/to/background.ts'