Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

google chrome extension - How can I listen to notifications?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can hook the webkitNotifications.createNotification function so that whenever a notification is created you run some particular code.

  1. 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;
         }
     })();
    
  2. Next, include notifhook.js in your web_accessible_resources list in your manifest.

  3. Finally, in a content script, inject a <script> element into the page with notifhook.js as its src:

     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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...