javascript - 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 生成的通知出现?
解决方案
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);
}
});
推荐阅读
- react-native - React-Native HighCharts 提升模块的使用
- javascript - 在 Angular 中使用 Google One Tap
- c++ - 在kali系统中如何解决c语言这个错误?
- r - 放大使用 ggplotly 生成的交互式绘图时的对象大小
- json - 如何在 Azure 流分析中展平嵌套的 json 数据
- linux - 基于多个条件的 DNS 转发(Linux Bind)
- python - 以 sr.Microphone() 作为源不工作
- android - Koin 共享依赖关系范围为嵌套图
- node.js - 使用 loopback4 解析 xml 请求正文
- c - 系统崩溃时 clflush 或 clflushopt 是原子的吗?