【发布时间】:2014-11-27 05:09:56
【问题描述】:
我正在尝试将消息从内容脚本发送到 chrome 扩展中的后台脚本,以触发丰富的通知打开。我已经可以做到这一点,但它破坏了我扩展的其余部分。
在我的内容脚本中,我调用了 chrome.extension.sendMessage,我在其中加载了我的扩展代码。这一切都很好,直到我添加了我的通知代码,我决定使用 chrome Rich Notifications API,因为我希望最终在我的通知中有按钮,并且我被引导相信只有后台脚本才能打开丰富的通知,因此消息的需要。如果我在 background.js 中注释掉 chrome.runtime.OnMessage.addListener 函数,我的扩展逻辑会再次正确加载,所以关于该调用的某些内容与 inject.js 中的 chrome.extension.sendMessage 函数冲突。
谁能解释为什么会发生这种情况以及如何解决它?
我的代码的简化版本如下:
manifest.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"
}});
【问题讨论】:
-
你的第一个
sendMessage没有类型字段,我猜这是你的听众要打破的东西(“无法读取未定义的属性'类型'”)。 -
感谢您的建议,我将 sendMessage 更新为使用 {type: "initialise"} 但我的扩展逻辑仍然无法运行。
-
控制台出现什么错误?
-
好的,终于搞清楚了如何查看 background.js 的控制台。没有错误,我在 background.js 的侦听器中添加了一个 console.log(response),我可以看到我的“初始化”和“通知”消息都通过了。我是否需要特别返回某些内容才能让我的加载消息在内容脚本上运行?
标签: javascript google-chrome-extension