【发布时间】:2012-08-29 05:26:03
【问题描述】:
我正在尝试实现我自己的 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"]
}
}
我在background.js 中给sendMessage 打电话
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"});
});
我得到的唯一错误是
端口错误:无法建立连接。接收端不 存在。
感谢您的帮助!
【问题讨论】:
-
后台页面加载很久才显示浏览器动作弹窗。显然,弹出脚本没有更改通过
chrome.extension.onMessage绑定事件监听器。 -
如前所述,这是基于事件触发的。由于事件发生在页面加载后的几秒钟内,是否仍然可以相信它没有被弹出窗口收听?
-
确保你说的是真的。您可以输入一个
alert('')对话框来查看这些方法是否以预期的顺序出现。旁注,您可以通过chrome.extension.getBackgroundPage()(从弹出窗口访问后台的全局window对象)和chrome.extension.getViews({type:'popup'})[0](如果存在弹出窗口的全局window对象,从背景页面)。 -
我刚刚对此进行了测试,实际上,弹出窗口中的任何操作都只能在它打开时触发。知道如何模拟消息发送吗?不幸的是,它与 getBackgroundPage() 和 getViews() 相同...仅在弹出窗口打开时起作用:(
-
“显然”也已被弃用,应避免使用。
标签: google-chrome google-chrome-extension messaging message-passing