【发布时间】:2017-02-01 14:25:16
【问题描述】:
我正在尝试使用 chrome 扩展捕获发送到我的 chrome 浏览器的推送通知,然后将其写入文件或在接收到它时运行代码。 我相信我遇到的问题对你们中的一些人来说很简单,所以我将分享我目前发现的内容和我的代码。
notifhook.js
(function() {
// save the original function
var origCreateNotif = notifications.createNotification;
// overwrite createNotification with a new function
notifications.createNotification = function(img, title, body) {
// call the original notification function
var result = origCreateNotif.apply(this, arguments);
alert("Function was called");
// bind a listener for when the notification is displayed
result.addEventListener("display", function() {
alert("Triggered code");
// do something when the notification is displayed
});
return result;
}
})()
manifest.json
{
"name": "Push",
"description": "Relay push notifications",
"version": "3.0",
"permissions": ["notifications"],
"web_accessible_resources": ["notifhook.js"],
"content_scripts" : [{
"run_at" : "document_start",
"matches" : ["<all_urls>"],
"js" : ["inject.js"]
}],
"manifest_version": 2
}
注入.js
var s = document.createElement("script");
s.src = chrome.extension.getURL("notifhook.js");
document.documentElement.appendChild(s);
使用的大部分代码都取自这里: How can I listen to notifications?
我正在使用这个 webapp 来测试我的扩展: http://ttsvetko.github.io/HTML5-Desktop-Notifications/
所以,据我所知,目前正在发生的事情是包含我的主要功能的块被添加到网页中就好了 因为我可以在它开始时发出警报,并且在每次页面加载时都会触发它。
失败的原因是当我收到推送通知时,事件侦听器无法正常工作或我的函数名称错误。我在某处读到 webkitNotifications 被替换为“通知”。
非常感谢任何帮助。
【问题讨论】:
-
Web 应用关闭时是否会触发推送通知?如果是这样,推送通知将在 servis worker 中并且您的脚本不会触发,您将需要用您的脚本覆盖 service worker 的注册并使用原始调用 importScripts。
-
只要 chrome 处于打开状态,我就会收到通知。不过,您将如何覆盖注册?
-
打开是指页面而不是浏览器,如果您在关闭浏览器选项卡时收到通知(如在 facebook 上),则表示通知来自服务人员。
标签: google-chrome google-chrome-extension push-notification notifications record