尝试构建一个带有通知的 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/