[英]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.