如何在弹出消息后从内容脚本返回消息?

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

我正在将消息发送到正在制作的浏览器扩展程序中的内容脚本。然后,我需要将内容脚本检索到的值发送回弹出窗口。我知道内容脚本可以找到我要的值,因为当我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";
    }
});
javascript popup firefox-addon content-script browser-extension
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.