Search code examples
javascriptbackgroundfirefox-addonmessagingcontent-script

How to know which content script communicates with the background in a Firefox add-on?


According to this simple example: how to know which content script (which tab) is actually sending a message to the background (line 10)? For example with the tab id.


Solution

  • In the example for background-script.js, the portFromCS has a sender property: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/Port

    That sender is an object which contains tab and in particular tab.id https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/MessageSender

    /* background-script.js */
    browser.runtime.onConnect.addListener(port => {
        port.onMessage.addListener((msg) => {
            console.log("bg received", msg, "from tab", port.sender.tab.id);
        });
    });
    

    You can also do "one-off" or connection-less messages with browser.runtime.onMessage

    the handler has signature (msg, sender, reply), where sender is the same MessageSender object as above.