首页 > 解决方案 > 弹出消息后如何从内容脚本返回消息?

问题描述

我正在向正在制作的浏览器扩展中的内容脚本发送消息。然后,我需要将内容脚本检索到的值发送回弹出窗口。我知道内容脚本可以找到我要求的值,因为它正在打印我console.log的值。但是,我似乎无法让它返回这个值。

我对代码的基本设置如下:

// popup.js
valueOnWebpage = browser.tabs.query({active: true, currentWindow: true})
        .then(updateLabelInPopup)
        .catch(printError);

function updateLabelInPopup(tabs) {
browser.tabs.sendMessage(tabs[0].id, {command: "getValueFromWebpage"})
            .then(function (result) {
                console.log("Result: " + result); // this is logging `"Result: undefined"`
                document.getElementById("id-of-element-in-popup").innerHTML = result;
            }).catch(function (err) {
                console.log("ERROR: ", err);
            });

}
// content_script.js
function getValueFromWebpage() {
    return document.getElementById("id-of-element-value-i-want").innerText;
}

browser.runtime.onMessage.addListener((message) => {
    if (message.command === "getValueFromWebpage") {
        valueFromPage = getValueFromWebpage();
        console.log("Ran by message listener ", valueFromPage); // This is in fact logging what I want
        return valueFromPage; // I want this so that I can do something with it in the popup
    } else {
        return "Not a recognized command";
    }
});

标签: javascriptpopupfirefox-addoncontent-scriptbrowser-extension

解决方案


我将值作为回调函数的结果返回。这不会返回到弹出脚本!呸!您必须将其作为消息传递给弹出脚本。出于某种原因,我认为不允许从内容脚本到弹出窗口的消息传递。


推荐阅读