无法将消息从 Chrome 扩展程序中的弹出窗口.js发送到后台.js

Fail to send message from popup.js in Chrome extension to background.js

本文关键字:js 窗口 后台 消息 Chrome 程序 扩展      更新时间:2023-09-26

我希望从弹出窗口.js向后台发送消息.js。当我单击该按钮时,消息将发送到后台.js,它将为我的指定网站打开一个新选项卡。我检查了弹出窗口.js和背景.js发现它们都还可以,只是无法将消息从弹出窗口.js发送到后台.js。

弹出窗口.js

window.onload=function()
{
     document.getElementById("submit").onclick=function()
  {
     chrome.extension.sendMessage({command:"start"});
  }
}

背景.js

chrome.extension.onMessage.addListener(
    function(request,sender,sendResponse)
    {
        switch(request.command)
        {
            case "command":
                openTab();
            break;
        }
        return true;
    }
);
var openTab=function()
{
    chrome.windows.create
    (
        {
            url:"http://www.baidu.com",
            tabId:1
        }
    );
};

您的代码中有一个小错误:在用于接收background.js脚本中的消息的函数中,您正在使用变量 request.command 上的 switch 语句,但是,在其中,您正在检查case "command",而您应该检查case "start",因为您正在发送一条{command: "start"}的消息

收到消息,但根据不匹配的字符串进行检查,显然您的openTab()函数永远不会被调用。

要解决此问题,您可以:

  • 更改您从 popup.js 发送的消息,如下所示:

    chrome.runtime.sendMessage({command: "command"});
    
  • 或者更改background.js脚本中的 case 语句:

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        switch(request.command) {
            case "start":
                openTab();
                break;
        }
        return true;
    });
    

无论如何,我强烈建议您使用chrome.runtime API而不是chrome.extension,这已经过时了。