一个人怎么用Chrome desktop notifications?我希望在我自己的代码中使用它.
Update:这里有a blog post个例子来解释webkit通知.
一个人怎么用Chrome desktop notifications?我希望在我自己的代码中使用它.
Update:这里有a blog post个例子来解释webkit通知.
在现代浏览器中,有两种类型的通知:
API调用采用相同的参数(除了操作——在桌面通知中不可用),这些参数在MDN和Google's Web Fundamentals站点上都有详细的文档记录.
下面是Chrome、Firefox、Opera和Safari的desktop个通知的工作示例.请注意,出于安全原因,从Chrome 62permission for the Notification API may no longer be requested from a cross-origin iframe开始,所以我们不能使用StackOverflow的代码片段演示.您需要将此示例保存在站点/应用程序上的HTML文件中,并确保使用localhost://
或HTTPS.
// request permission on page load
document.addEventListener('DOMContentLoaded', function() {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== 'granted')
Notification.requestPermission();
});
function notifyMe() {
if (Notification.permission !== 'granted')
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: 'Hey there! You\'ve been notified!',
});
notification.onclick = function() {
window.open('http://stackoverflow.com/a/13328397/1269037');
};
}
}
<button onclick="notifyMe()">Notify me!</button>
我们使用的是W3C NotificationsAPI.不要将这与Chrome extensions notifications API混淆,后者是不同的.Chrome扩展通知显然只适用于Chrome扩展,不需要用户的任何特殊许可.
W3C通知可在许多浏览器中使用(请参阅caniuse上的支持),并且需要用户权限.作为一种最佳实践,不要马上申请许可.Explain to the user first why they would want notifications,另见push notifications patterns.
请注意,由于版本为this bug,Chrome不支持Linux上的通知图标.
通知支持一直在不断变化,各种API在过go 几年中被弃用.如果你很好奇,可以查看之前对这个答案的编辑,看看在Chrome中使用了什么,并了解丰富的HTML通知的故事.
现在最新的标准是https://notifications.spec.whatwg.org/.
至于为什么会有两个相同效果的不同电话,这取决于你是不是服务人员-参见this ticket I filed while I worked at Google.
另请参见notify.js以了解辅助器库.