javascript - 弹出消息后如何从内容脚本返回消息?
问题描述
我正在向正在制作的浏览器扩展中的内容脚本发送消息。然后,我需要将内容脚本检索到的值发送回弹出窗口。我知道内容脚本可以找到我要求的值,因为它正在打印我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";
}
});
解决方案
我将值作为回调函数的结果返回。这不会返回到弹出脚本!呸!您必须将其作为消息传递给弹出脚本。出于某种原因,我认为不允许从内容脚本到弹出窗口的消息传递。
推荐阅读
- firebase - 或在 Firestore 中使用 2 个不同字段进行查询
- python - 类属性和实例属性
- python - DatabaseError:1366(HY000):不正确的整数值:第 1 行的列“STU_SCHOOLID”的“STUSCHOOLID 错误”
- vba - 刷新 Essbase/SmartView 表时如何抑制警报?
- python - 我正在搜索但是在打印时为什么第二个输入也进来了
- python - 数据框将行中的值转换为唯一列
- python - 有没有办法在在 python 中使用硒?
- javascript - pure-react-carousel:所有幻灯片可见
- python - 如何在数据库中的每个条目上运行刮板?
- prolog - 在 Prolog 中使用 DCG 时,有没有一种方法可以递归调用非终结符号?