背景到前景 chrome.runtime.onMessage() 失败

background to foreground chrome.runtime.onMessage() failing

检查 google chrome 扩展代码 bellow.Here 我只是想将基本字符串消息从后台发送到前台,但我在选项卡控制台中收到错误消息:Error in event handler: TypeError: Error in invocation of tabs.sendMessage(integer tabId, any message, optional object options, optional function callback): No matching signature. 我在这里做什么有什么问题吗?

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);
  });

您传递了一个具有属性 tabId 的对象。 应该是数字类型的变量。

正确的用例:

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

API 文档:

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