[英]chrome extension notification not showing
试图建立一个带有通知的chrome扩展程序,我想要一个显示通知的按钮。 这是HTML代码:
<div><button onclick="notifyMe()">Notify me!</button></div>
该按钮显示在扩展名中,但是当我按下它时,什么也没有发生。 这是我的js代码:
function notifyMe() {
var notification = new Notification("Hi there!");
}
我是否缺少任何js代码? 我不知道
不确定我是否遵循正确,但是如果您想显示chrome通知,实际上有chrome通知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 });
}
如果要使用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!");
}
}
您的代码正在调用桌面通知API,而不是Chrome通知API:
var notification = new Notification("Hi there!");
显然Google修改了chrome扩展程序中的权限级别(在Chrome 43及更高版本中可完美运行)。 只需在manifest.json中包含以下行,即可使用桌面通知API(以及Chrome通知API):
"permissions": [ "notifications", ...etc... ],
将通知添加到权限范围后,可以检查Notification.permission返回“已授予”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.