我正在尝试在 Chrome 中创建通知。
我已经编写了这个简单的代码,但 CHrome 中显示了通知,而 checkPermission()
返回良好 0
。
我做了与此网站(示例)相同的操作,它在我的 Chrome 浏览器中运行良好。
if (window.webkitNotifications.checkPermission() == 0) {
window.webkitNotifications.createNotification("icon.png", "title", "text").show();
} else {
window.webkitNotifications.requestPermission();
}
问题出在哪里?
[编辑:问题已解决]
事实上,我允许在 Chrome 设置中显示来自所有网站的通知,现在,它工作正常!
最佳答案
请求权限仅适用于用户手势(请参阅下面的问题,并引用文档)。
简而言之,您需要注册一个点击事件或类似的事件然后请求权限。
document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
var notification = window.webkitNotifications.createNotification(
'icon.png', 'Notification Title', 'Notification content...');
notification.show();
} else {
window.webkitNotifications.requestPermission();
}
}, false);
这是一个jsfiddle
Webkit notifications requestPermission function doesn't work
requestPermission Requests that the user agent ask the user for permission to show notifications from scripts. This method should only be called while handling a user gesture; in other circumstances it will have no effect. This method is asynchronous. The function provided in callback will be invoked when the user has responded to the permission request. If the current permission level is PERMISSION_DENIED, the user agent may take no action in response to requestPermission.
关于javascript - 通知 HTML5 是否可以在 Chrome 中本地运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22810288/