我是新增的浏览器通知。如何使用浏览器通知?我无法弄清楚从哪里开始。任何人都可以提供关于如何开始这个的建议。
答案 0 :(得分:0)
要使浏览器通知正常工作,您的网站或应用程序应通过https提供,否则浏览器不会允许它
mesg = {
title: "notification title",
body: "notification body",
icon: "location to an .ico image",
timer: true //for auto closing
}
// Let's check if the browser supports notifications
if (!('Notification' in window)) {
console.log('Browser does not support this feature.');
}else if (Notification.permission === 'granted') {
Notification.requireInteraction = false;
if (mesg.title !== 'undefined') {
const notification = new Notification(mesg.title, {
body: mesg.body,
icon: mesg.icon
});
if (mesg.timer) {
setTimeout(function () {
notification.close();
}, 5000);
}
return notification;
}// close if undefined
} else if (Notification.permission !== 'denied') {
alert('Please click Allow for enabling browser notifications');
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === 'granted') {
if (mesg.title !== 'undefined') {
const notification = new Notification(mesg.title, {
body: mesg.body,
icon: mesg.icon
});
if (mesg.timer) {
setTimeout(function () {
notification.close();
}, 5000);
}
return notification;
}// close if undefined
} else {
alert('Permission Denied :[');
}
});
}
我将此用于我的应用程序,您可以重构它以删除重复的代码。
答案 1 :(得分:0)
检查Notification API是否有参考资料
代码申请许可
document.addEventListener('DOMContentLoaded', function () {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
});
并显示通知
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'Icon Link',
body: "Notification Body",
});
notification.onclick = function () {
window.open("Href Here");
};
}
答案 2 :(得分:0)
例如
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== "denied") {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
}
notifyMe();
更多信息https://developer.mozilla.org/id/docs/Web/API/notification