chrome.extension.onMessage.addListener vs chrome.runtime.onMessage.addListener on manifest v3

Viewed 1819

Which function should I use for manifest v3 between chrome.extension.onMessage.addListener() and chrome.runtime.onMessage.addListener()?

Thanks.

1 Answers

Here's how you add a message Listener with manifest v3.

chrome.runtime.onMessage.addListener( // this is the message listener
    function(request, sender, sendResponse) {
        if (request.message === "messageSent")
            runThisFunction();
    }
);

To send a message, it depends if you're sending it from the Content Script or from the background Script.

From the Content Script:

chrome.runtime.sendMessage({message: "messageSent"}, function (response) {
    console.log(response);
});

From the background Script:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, 
        {
            message: "messageSent"
        }, function(response) {})
})

Here are the links to the official docs [https://developer.chrome.com/docs/extensions/mv3/messaging][1]

Related