我该如何收听通知?

Ale*_*tri 3 google-chrome-extension

有没有办法让扩展程序为浏览器通知添加监听器并访问它?我正在尝试使用Google日历的通知来启动自定义功能.

aps*_*ers 10

您可以挂钩该webkitNotifications.createNotification函数,以便在创建通知时运行某些特定代码.

  1. 创建一个名为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;
        }
    })();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 接下来,notifhook.jsweb_accessible_resources清单中列入清单.

  3. 最后,在内容脚本,注入<script>元素到页面notifhook.jssrc:

    var s = document.createElement("script");
    s.src = chrome.extension.getURL("notifhook.js");
    document.documentElement.appendChild(s);
    
    Run Code Online (Sandbox Code Playgroud)

您可能只想notifhook.js用作内容脚本,但这不起作用,因为内容脚本和网页具有单独的执行环境.覆盖内容脚本的版本webkitNotifications.createNotification根本不会影响Google日历页面.因此,您需要通过<script>标记注入它,这将影响页面和内容脚本.