Search code examples
javascriptgoogle-chromegoogle-chrome-extension

background to foreground chrome.runtime.onMessage() failing


Check the google chrome extension code bellow.Here i am simply trying to send a basic string message from background to foreground but i am getting error in tab console: Error in event handler: TypeError: Error in invocation of tabs.sendMessage(integer tabId, any message, optional object options, optional function callback): No matching signature. Whats wrong i am doing here any idea?

manifest.json:

{
    "name": "obj ext",
    "description": "my ext",
    "version": "0.1.0",
    "manifest_version": 2,
    "icons": {
        "16": "./obj-16x16.png",
        "32": "./obj-32x32.png",
        "48": "./obj-48x48.png",
        "128": "./obj-128x128.png"
    },
    "background":{
        "scripts":["./background.js"]
    },
    "options_page":"./options.html",
    "browser_action":{
        "default_popup": "popup.html"
    },
    "permissions":[
        "tabs",
        "https://www.google.com/"
    ]
}

background.js:

chrome.tabs.onActivated.addListener(tab => {
   

    console.log(tab.tabId);
    chrome.tabs.sendMessage(
        {tabId: tab.tabId},
        {message: 'Hello'}
      );

 
});

foreground.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    
    console.log(message);
  });

Solution

  • You passed an object with attribute tabId. It should be a number type variable.

    Correct use case:

    // other code
    chrome.tabs.sendMessage(
            tab.tabId,
            {message: 'Hello'}
    );
    // other code
    

    API doc:

    chrome.tabs.sendMessage(
      tabId: number, // Pay attention here
      message: any,
      options?: object,
      responseCallback?: function,
    )