尝试使用通知构建Chrome扩展程序,我想要一个显示通知的按钮。这是HTML代码:
<div><button onclick="notifyMe()">Notify me!</button></div>
此按钮显示在扩展程序中,但是当我按下它时,没有任何反应。这是我的js代码:
function notifyMe() {
var notification = new Notification("Hi there!");
}
我错过了任何js代码吗?我不知道
答案 0 :(得分:1)
不确定我是否正确关注,但如果您想要显示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 });
}
如果您想使用Notification
,首先要求使用权限(取自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!");
}
}
答案 1 :(得分:0)
您的代码正在调用桌面通知API,而不是Chrome通知API:
var notification = new Notification("Hi there!");
显然,Google修改了Chrome扩展程序的权限级别(在Chrome 43 +中完美运行)。只需在manifest.json中包含此行,桌面通知API即可使用(以及Chrome通知API):
"permissions": [ "notifications", ...etc... ],
向权限范围添加通知,您可以检查Notification.permission返回“已授予”。