gpt4 book ai didi

javascript - 调用后编辑 Chrome 通知?

转载 作者:行者123 更新时间:2023-12-02 13:56:41 24 4
gpt4 key购买 nike

我的 Chrome 扩展程序使用通知。我调用他们:

function notifyMe(message) {
if (!Notification) {
alert('No desktop notifications possible!');
return;
}

if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Bot success!', {
icon: 'https://material-design.storage.googleapis.com/publish/material_v_9/0Bx4BSt6jniD7blViQzF0azNqZU0/style_icons_system_intro_principles_consistent.png',
body: message,
});

setTimeout(function() { notification.close() }, 5000);

notification.onclick = function () {
window.open("http://google.com");
};

}

}

notifyMe("I am a notification!");

当通知已经存在时,有没有办法更改消息、图标和标题?有没有办法从另一个函数关闭它,而不是函数本身内部的 5000 毫秒超时?

我尝试了一些通过定义var notification从外部关闭它的方法;在我的脚本开头允许从任何地方访问,但这效果不太好。

这可能很明显,但我对 JS 仍然很陌生。对此感到抱歉!

感谢任何帮助!

最佳答案

您正在使用(网络)Notification API 创建通知,不是特定于扩展名 chrome.notifications API .考虑到这一点:

And is there a way to close it down from another function instead of the 5000ms timeout inside the function itself?

只要存储构造函数返回的 notification 对象,就可以随时调用 notification.close()

I tried a few things about closing it from the outside by defining var notification; at the beginning of my script to allow access from everywhere, but this didn't work too well.

这是一个有效的策略;但是,如果您在函数中再次编写 var notification ,您将不再访问全局 notification 变量,而是创建一个具有相同名称的新本地变量。如果您有全局变量,请避免在其他任何地方添加 var

可能想查看You Don't Know JS: Scope & Closures如果您有兴趣更深入地了解作用域在 JS 中的工作原理

Is there a way to change message, icon and title when the notification is already there?

您无法编辑由通知 API 创建的现有通知 - 创建后其所有属性都是只读的,并且不提供更新方法。

但是,您可以 replace a notification如果您使用相同的 tag attribute 创建一个新的:

new Notification('One', {
tag: "replaceMe"
});
new Notification('Two', {
tag: "replaceMe"
});
// Will result in only one notification, "Two", being shown
<小时/>

考虑使用chrome.notifications API为了您的目的。它比 Notifications API 提供了更多功能,例如按钮(至少在 Chrome 中 - 如果您想与 Firefox 共享代码库,那么优势就不那么明显了),并且不需要运行时权限请求.

关于javascript - 调用后编辑 Chrome 通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40651240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com