gpt4 book ai didi

javascript - 从内容脚本向后台脚本发送消息会破坏 chrome 扩展

转载 作者:数据小太阳 更新时间:2023-10-29 03:52:58 25 4
gpt4 key购买 nike

我正在尝试将消息从内容脚本发送到 chrome 扩展中的后台脚本,该扩展会触发丰富的通知打开。我已经可以做到这一点,但它破坏了我扩展的其余部分。

在我的内容脚本中,我调用了 chrome.extension.sendMessage,我在其中加载了我的扩展代码。这一切都很好,直到我添加了我的通知代码,我决定使用 chrome Rich Notifications API,因为我最终希望在我的通知中有按钮,并且我相信只有后台脚本才能打开丰富的通知,因此消息的需要。如果我注释掉 background.js 中的 chrome.runtime.OnMessage.addListener 函数,我的扩展逻辑将再次正确加载,因此该调用的某些内容与 inject.js 中的 chrome.extension.sendMessage 函数冲突。

谁能解释为什么会发生这种情况以及如何解决?

我的代码的简化版本如下:

list .json

{
"name": "Test",
"version": "0.0.1",
"manifest_version": 2,
"description": "Test
"permissions": [
"notifications"
],
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": [
"mywebsite/*"
],
"js": [
"inject.js",
]
}
],
"web_accessible_resources": [
"notificationIcon.png"
]
}

background.js

chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.type == "notification")
chrome.notifications.create('notification', request.options, function() { });
});

注入(inject).js

chrome.extension.sendMessage({}, function(response) {
//code to initialize my extension
});

//code to send message to open notification. This will eventually move into my extension logic
chrome.runtime.sendMessage({type: "notification", options: {
type: "basic",
iconUrl: chrome.extension.getURL("icon128.png"),
title: "Test",
message: "Test"
}});

最佳答案

问题是因为我在 background.js 中的监听器没有返回响应。所以我的 chrome.extension.sendMessage 的函数响应从未被执行。

我将 background.js 更改为:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "worktimer-notification")
chrome.notifications.create('worktimer-notification', request.options, function() { });

sendResponse();
});

关于javascript - 从内容脚本向后台脚本发送消息会破坏 chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156978/

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