gpt4 book ai didi

google-chrome - 将消息从 background.js 传递到 popup.js

转载 作者:行者123 更新时间:2023-12-04 00:31:14 28 4
gpt4 key购买 nike

我正在尝试实现我自己的 chrome 扩展,在某个事件上,创建一个浏览器通知并用 background.js 中计算的数据填充弹出窗口
这是我的 manifest.json文件:

{
"name": "Dummy name",
"description": "Description",
"manifest_version": 2,
"version": "1.1.3",
"icons": {
"16": "icon_16.png",
"48": "icon_48.png",
"128": "icon_128.png",
"256": "icon_256.png"
},
"browser_action": {
"default_icon": "icon_48.png",
"default_title": "Test",
"default_popup": "popup.html"
},
"permissions": ["background","webRequest","webRequestBlocking","webNavigation","tabs","notifications"],
"background": {
"scripts":["jquery-1.8.1.min.js","classy.js","background.js"]
}
}
我的电话 sendMessagebackground.js
show : function(result) {
var that = this;
chrome.extension.sendMessage({greeting: "hello"}, function(response) {
console.log(response);
});

if(window.webkitNotifications) {
var notification = webkitNotifications.createHTMLNotification('notification.html');
notification.show();
setTimeout(function(){
notification.cancel();
}, '7000');
}
}
我的消息监听器在 popup.js (来自 chrome 扩展示例)
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
我得到的唯一错误是

Port error: Could not establish connection. Receiving end does notexist.


感谢您的帮助!

最佳答案

弹出窗口没有选项卡 ID,因此您会收到错误消息。

您可以使用 chrome.runtime.sendMessagechrome.runtime.onMessage.addListener在这种情况下。

所以在 background.js

chrome.runtime.sendMessage({
msg: "something_completed",
data: {
subject: "Loading",
content: "Just completed!"
}
});

而在 popup.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.msg === "something_completed") {
// To do something
console.log(request.data.subject)
console.log(request.data.content)
}
}
);

我希望它对你有帮助。

谢谢,

关于google-chrome - 将消息从 background.js 传递到 popup.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265403/

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