gpt4 book ai didi

javascript - Chrome 扩展消息传递无响应-告别 : undefined

转载 作者:行者123 更新时间:2023-12-03 03:23:30 28 4
gpt4 key购买 nike

我正在尝试在 Chrome 扩展程序中传递消息。我按照这个例子(see here)-:

内容脚本:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});

背景:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});

popup.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
console.log("message recive")
sendResponse({farewell: "goodbye"});
});

尽管我进行了复制粘贴,但消息并未发送。弹出错误:

事件处理程序中出现错误(未知):TypeError:无法读取未定义的属性“告别”

哪里错了?

最佳答案

弹出窗口在关闭时不存在。

因此,在发送消息时,可能没有人在监听,因此使用 undefined 作为响应调用回调(并使用 chrome.runtime.lastError) > 设置)。

从架构的 Angular 来看,后台页面是始终可用于处理消息的页面;因此,onMessage 监听器在大多数(不是全部)情况下都在那里更好。

我建议您也看看这个问题,我在其中更详细地解释了一些概念:Pass a variable from content script to popup .

此外,为了以防万一,所有这些问候语示例代码只是一个示例;您可以传递任何可 JSON 序列化的内容。

关于javascript - Chrome 扩展消息传递无响应-告别 : undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46462484/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com