简体   繁体   English

chrome扩展名通知未显示

[英]chrome extension notification not showing

Trying to build a chrome extension with notifications, and I would like a button that displays a notification. 试图建立一个带有通知的chrome扩展程序,我想要一个显示通知的按钮。 This is the HTML code: 这是HTML代码:

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

This button shows in the extension, but when I press it, nothing happens. 该按钮显示在扩展名中,但是当我按下它时,什么也没有发生。 Here is my js code: 这是我的js代码:

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

Am I missing any js code? 我是否缺少任何js代码? I have no idea 我不知道

Not sure if I'm following correctly but if you want to show a chrome notification there's actually the chrome notifications API 不确定我是否遵循正确,但是如果您想显示chrome通知,实际上有chrome通知API

I'd do the following: 我将执行以下操作:

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

JS 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 });
}

If you want to use the Notification you have to ask for permissions first to use it (taken from the Web Notifications article on MDN ): 如果要使用Notification ,则必须先请求权限才能使用它(摘自MDN上Web通知文章 ):

// 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!");
  }
}

Your code is calling the Desktop Notification API and not the Chrome Notification API: 您的代码正在调用桌面通知API,而不是Chrome通知API:

var notification = new Notification("Hi there!");

Apparently Google modified the level of permission in chrome extension (works perfectly in Chrome 43 +). 显然Google修改了chrome扩展程序中的权限级别(在Chrome 43及更高版本中可完美运行)。 Just include this line in your manifest.json, and Desktop notifications API will work (as well as the Chrome Notification API): 只需在manifest.json中包含以下行,即可使用桌面通知API(以及Chrome通知API):

"permissions": [ "notifications", ...etc... ],

Adding notifications to the permissions scopes, you can check Notification.permission returns "granted". 将通知添加到权限范围后,可以检查Notification.permission返回“已授予”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM