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 if the user is okay to get some notification
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
// Note, Chrome does not implement the permission static property
// So we have to check for NOT 'denied' instead of 'default'
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// Whatever the user answers, we make sure we store the information
if(!('permission' in Notification)) {
Notification.permission = permission;
}
// If the user is okay, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
} else {
alert(`Permission is ${Notification.permission}`);
}
}
在现代浏览器中,有两种类型的通知。
API调用需要相同的参数(除了动作--在桌面通知上不可用),这些参数在MDN上有很好的记录,对于服务工作者,在Google's Web Fundamentals网站上也有记录。
下面是一个用于Chrome、Firefox、Opera和Safari的桌面通知的工作实例。请注意,由于安全原因,从Chrome 62开始,通知API的权限可能不再从跨源iframe请求,所以我们不能用StackOverflow的代码片段来演示。你需要在你的网站/应用程序的HTML文件中保存这个例子,并确保使用
localhost://
或HTTPS。请查看设计和API规范(它仍然是一个草案),或从(不再提供的页面)查看源码,以获得一个简单的例子。它主要是对`window.webkitNotifications.createNotification'的调用。
如果你想要一个更强大的例子(你想创建自己的谷歌浏览器扩展,并想知道如何处理权限、本地存储等问题),请查看Gmail Notifier Extension:下载crx文件而不是安装它,解压并阅读其源代码。
似乎
window.webkitNotifications
已经被废弃并删除。 然而,有一个新的API,而且似乎在最新版本的Firefox中也能使用。codepen
我喜欢:http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples,但它使用了旧的变量,所以演示不能再使用。`webkitNotifications`现在是`Notification`。
我做了这个简单的通知包装器。 它可以在Chrome、Safari和Firefox上使用。
可能在Opera、IE和Edge上也可以,但我还没有测试过。
只要从这里得到notify.js文件https://github.com/gravmatt/js-notify,然后把它放到你的页面中。
1:
在Bower上获取
这就是它的工作原理。
你必须设置标题,但作为第二个参数的json对象是可选的。
这里有很好的API文档。
[https://developer.chrome.com/apps/notifications][1]
而且,谷歌的官方视频解释。
[https://developers.google.com/live/shows/83992232-1001][2]
[1]: https://developer.chrome.com/apps/notifications [2]: https://developers.google.com/live/shows/83992232-1001
Notify.js 是一个围绕新的 webkit 通知的包装器。 它的工作原理很好。
http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/