首页 > 解决方案 > For-Loop 通知未出现

问题描述

我设置了一系列 For-Loop 生成的链接,这些链接应该以通知的形式显示自定义消息。

显示通知的功能在我的后台事件页面(eventPage.js)中:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if (request.todo == "notification"){
        var notifOptions = {
            type: 'basic',
            iconUrl: 'icon48.png',
            title: request.ttl,
            message: request.msg
        };
        chrome.notifications.create('notti', notifOptions);
    }
});

同时,在内容页面(content.js)上,有两个条件链接到这个函数:


第一的:

if (request.todo == "full"){
        chrome.runtime.sendMessage({todo: "notification", ttl: 'Title', msg: 'Test!'});
    }

第一个功能有效,并且通知显示没有任何问题(因此,权限等没有问题)。


第二个条件是不起作用的:

 if(request.todo == "quick"){
        for (let i = 0; i < wrds.length; i++) {
            var entry = "#"+wrds[i];
            if ($(entry).length) {
                $(entry).on("click", function() {
                    var msg = prns[i]+'\n'+defs[i];
                    chrome.runtime.sendMessage({todo: "notification", ttl: 'Title', msg: msg});
                    alert(msg);
                }); 
            }
        }}

此条件尝试在 for 循环中设置一系列通知。问题是,虽然警报运行良好,但通知根本不会出现。

如何让 for-loop 生成的通知出现?

标签: javascriptgoogle-chrome-extension

解决方案


for 循环版本不起作用,因为通知标题需要是唯一的。

为了使通知始终出现,无论它以前是否出现过,都需要使用唯一的名称来创建它。

为了解决这个问题,我决定让名字成为一个唯一的时间戳。

for (let i = 0; i < wrds.length; i++) {
            var entry = "#"+wrds[i];
            if ($(entry).length) {
                $(entry).on("click", function() {
                    var timestamp = String(new Date().getTime());
                    var msg = prns[i]+'\n'+defs[i];
                    chrome.runtime.sendMessage({todo: "notification", ttl: wrds[i], msg: msg, stamp:timestamp});
                }); 
            }
        }

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if (request.todo == "notification"){
        var notifOptions = {
            type: 'basic',
            iconUrl: 'icon48.png',
            title: request.ttl,
            message: request.msg
        };
        chrome.notifications.create(request.stamp, notifOptions);
    }
});

推荐阅读