从Chrome扩展中的popup.js发送消息到background.js

问题描述 投票:0回答:1

在 Chrome 扩展程序中从 popup.js 向 background.js 发送消息(并获取响应)的正确方法是什么?我尝试的每种方法最终都会出现以下错误:

“端口:无法建立连接。接收端不存在。”

我更喜欢使用 chrome.extension.sendMessage() 而不是 chrome.extension.connect() 和 port.postMessage(),但这两种方法似乎都不起作用。

我想要做的是在 popup.html 中连接一个按钮来调用 popup.js 中的一些 javascript,它会回调background.js,以获取有关 topMost 的 currentTab() 的信息(即:获取当前 URL 字符串以显示在 popup.html 中)

现在在 popup.js (连接到按钮的操作)我有:

function getURL()
{
   chrome.extension.sendMessage({greeting: "GetURL"}, 
          function(response) { tabURL = response.navURL });

   $("#tabURL").text(tabURL);
}

background.js 我有:

chrome.extension.onMessage.addListener( function(request,sender,sendResponse)
{
    if( request.greeting == "GetURL" )
    {
        var tabURL = "Not set yet";
        chrome.tabs.getCurrent(function(tab){
            tabURL = tab.url;
        });

        sendResponse( {navURL:tabURL} );
    }
}

有什么想法吗?

google-chrome google-chrome-extension
1个回答
39
投票

为了澄清一下,我们谈论的是 browserAction 的弹出页面和后台脚本之间的通信?

无论如何,你的代码中有很多错误。

首先你完全忽略了chrome api中的所有回调都是异步的事实。

在后台页面

    var tabURL = "Not set yet";
    chrome.tabs.getCurrent(function(tab) {
        tabURL = tab.url;
    }); //this will be invoked somewhere in the future

    sendResponse({ navURL: tabURL }); 
    //navUrl will be always Not set yet because callback of getCurrent hasn't been called yet

popup.js 中相同

chrome.runtime.sendMessage({ greeting: "GetURL" }, 
          function(response) { tabURL = response.navURL });//callback will be invoked somewhere in the future

$("#tabURL").text(tabURL)//tabURL will display something totally different from what you have been expected

第二个错误是

chrome.tabs.getCurrent
不会为您提供用户在主窗口中选择的当前选项卡。 docs 说:

获取发出此脚本调用的选项卡。或许 如果从非选项卡上下文调用,则未定义(例如:背景 页面或弹出视图)。

因此,您的所有请求都将是未定义的,因为您在后台页面中调用它。您需要做的是使用方法 chrome.tabs.query 来获取当前活动的选项卡。

因此,解决所有问题后,新代码应该如下所示:

背景.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
    if(request.greeting === "GetURL")
    {
        var tabURL = "Not set yet";
        chrome.tabs.query({ active: true }, function(tabs) {
            if(tabs.length === 0) {
                sendResponse({});
                return;
            }
            tabURL = tabs[0].url;
            sendResponse({ navURL: tabURL });
        });        
    }
});

popup.js

function getURL() {
    chrome.runtime.sendMessage({greeting: "GetURL"},
        function (response) {
            tabURL = response.navURL;
            $("#tabURL").text(tabURL);
        });
}
© www.soinside.com 2019 - 2024. All rights reserved.