javascript - chrome 扩展通知未显示

标签 javascript html google-chrome notifications

尝试构建一个带有通知的 Chrome 扩展,我想要一个显示通知的按钮。这是 HTML 代码:

    <div><button onclick="notifyMe()">Notify me!</button></div>

此按钮显示在扩展程序中,但当我按下它时,没有任何反应。这是我的 js 代码:

function notifyMe() {
    var notification = new Notification("Hi there!");
}

我是否缺少任何 js 代码?我不知道

最佳答案

不确定我是否正确理解,但如果你想显示 Chrome 通知,实际上有 chrome notifications API

我会执行以下操作:

<div><button onclick="notifyMe()">Notify me!</button></div>

JS

function notifyMe() {
  chrome.notifications.create('some id for this notification', {
    type: 'basic', // "basic", "image", "list", or "progress"
    title: 'a title for this notification',
    message: 'the message you want to show'
  }, function () { // called when the notification is created });
}

如果您想使用通知,您必须先请求权限才能使用它(取自 Web Notifications article on MDN ):

// At first, let's check if we have permission for notification
// If not, let's ask for it
if (window.Notification && Notification.permission !== "granted") {
  Notification.requestPermission(function (status) {
    if (Notification.permission !== status) {
      Notification.permission = status;
    }
  });
}

function notifyMe() {
  if (window.Notification && Notification.permission === "granted") {
    var n = new Notification("Hi!");
  }
}

关于javascript - chrome 扩展通知未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28788720/

相关文章:

php - 如何让Mysql加载图片更快?

javascript - ASP.NET 包在部署时不起作用(调试 ="false")

javascript - 如何在 Chrome 扩展程序中覆盖下载过程

html - CSS3 卡翻转故障

html - 为什么 flex-box 会溢出包装器?

google-chrome - 什么是最小的有效域名?

javascript - yii2 dropDownList 当从所有索引获取值时总是晚一步

javascript - 使用 JavaScript 提交后清除输入字段

javascript - Chrome 分析器 - 为什么功能有时会停止一小段时间?

css - 如何跨浏览器模糊图像?