javascript - 调用后编辑 Chrome 通知?

标签 javascript google-chrome google-chrome-extension notifications

我的 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/

相关文章:

google-chrome - 调整大小(按比例缩小)图像锯齿状,重绘平滑(不重新加载)

javascript - Chrome 扩展 - 使用 JQuery 在 content_scripts 上触发事件

google-chrome - 自托管和自动更新 Google Chrome 扩展

javascript - Chrome 扩展程序弹出窗口不起作用,点击事件未处理

javascript - Chrome 扩展程序表单保存错误

javascript - 自定义元框 > 18+ 弹出确认窗口

javascript - 将鼠标悬停在列表项上时更改背景图像

php - javascript 无法在 Google Chrome 上运行

python - 在 Windows 操作系统上使用 Python 在 Chrome 或 Firefox 中打开一个新的未聚焦选项卡

html - 多个电子邮件输入由具有不同名称/ID/占位符的自动填充填充