从WebExtension中的消息生成背景中的通知

时间:2018-06-17 07:07:33

标签: javascript notifications firefox-addon firefox-webextensions

所以我通过开发Mozilla FireFox的扩展来了解网络扩展世界。

作为扩展程序的一部分,我的主要内容脚本将使用browser.runtime.sendMessage()方法生成并发送消息:

console.log("<extension> is active.");
browser.runtime.sendMessage({
    notify: "<extension> is now active."
});

然后我有一个后台javascript页面正在侦听消息(使用runtime.onMessage.addListener()事件)假设以创建带消息文本的Notification对象。它还优雅地处理通知权限请求,如下所示:

function handleNotifications(request, sender, sendResponse) {
    console.log('Notify message generated by content script.');
    // Check if notification permissions have been granted
    if (Notification.permission === "granted"){
        // If yes, then create the notification
        var notification = new Notification(title, {
            icon: img,
            body: request.notify,
        });
    }

    // Otherwise, we must ask the user for permission
    else if (Notification.permission !== "denied"){
        Notification.requestPermission(function (permission){
            // If the user accepts, then create notifications
            if (permission === "granted") {
                var notification = new Notification(title, {
                    icon: img,
                    body: request.notify,
                });
            }
        });

    //If for some reason the user has *denied* notifications, alert them
    } else {
        alert("You have chosen to disable notifications. <extension> will still work, but will not inform you of outcomes.");
    }
}

// Create listener for messages from content script
browser.runtime.onMessage.addListener(handleNotifications);

根据MDN页面herehere的规范,我已经从头开始重写了一次背景代码。我也用Google搜索并确保我的manifest.json具有this stackoverflow article建议的notifications权限。

目前,我的代码将在名义上执行,据我所知;它生成警报和日志,并在内容脚本中调用时创建通知,但不在后台创建。我最好的猜测是背景监听器从未实际触发,但我不知道如何调试,除了我可以说我放在上面的背景片段中的console.log行从未出现在开发者控制台中。

0 个答案:

没有答案