我怎样才能听通知? [英] How can I listen to notifications?
问题描述
有没有扩展方法可以将侦听器添加到浏览器通知中,并访问它的内容?
我试图使用Google日历的通知来触发自定义函数。
您可以将 webkitNotifications.createNotification
函数,以便每当创建通知时运行一些特定的代码。
-
创建一个名为 notifhook.js 的文件:
(function(){
//保存原始函数
var origCreateNotif = webkitNotifications.createNotification;
//用新函数覆盖createNotification
webkitNotifications.createNotification = function(img,title,body) {
//调用原始通知函数
var result = origCreateNotif.apply(this,arguments);
//在侦听通知时绑定侦听器显示
result.addEventListener(display,function(){
//当通知显示时执行某些操作yed
//使用img,title和body来读取通知
//您的触发代码在这里!
});
返回结果;
}
})();
-
接下来,include
notifhook.js
在您的web_accessible_resources
列表中 最后,在 内容脚本 ,使用
notifhook.js 注入< script>
code>作为它的 src
: var s = document .createElement( 脚本);
s.src = chrome.extension.getURL(notifhook.js);
document.documentElement.appendChild(s);
您可能会试图使用 notifhook.js
作为您的内容脚本,但这不起作用,因为内容脚本和网页有分离的执行环境。覆盖内容脚本的 webkitNotifications.createNotification
版本根本不会影响Google日历页面。因此,您需要通过< script>
标记进行注入,这会影响页面和内容脚本。
Is there a way for an extension to add a listener to browser notifications, and access it content? I'm trying to use Google Calendar's notifications to fire a custom function.
You can hook the webkitNotifications.createNotification
function so that whenever a notification is created you run some particular code.
Create a file called notifhook.js:
(function() { // save the original function var origCreateNotif = webkitNotifications.createNotification; // overwrite createNotification with a new function webkitNotifications.createNotification = function(img, title, body) { // call the original notification function var result = origCreateNotif.apply(this, arguments); // bind a listener for when the notification is displayed result.addEventListener("display", function() { // do something when the notification is displayed // use img, title, and body to read the notification // YOUR TRIGGERED CODE HERE! }); return result; } })();
Next, include
notifhook.js
in yourweb_accessible_resources
list in your manifest.Finally, in a content script, inject a
<script>
element into the page withnotifhook.js
as itssrc
:var s = document.createElement("script"); s.src = chrome.extension.getURL("notifhook.js"); document.documentElement.appendChild(s);
You might be tempted to just use notifhook.js
as your content script, but that won't work because the content script and the web page have separate execution environments. Overwriting the content script's version of webkitNotifications.createNotification
won't affect the Google Calendar page at all. Thus, you need to inject it via <script>
tag, which will affect both the page and the content script.
这篇关于我怎样才能听通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!