javascript - 通知 HTML5 是否可以在 Chrome 中本地运行?

标签 javascript html google-chrome

我正在尝试在 Chrome 中创建通知。 我已经编写了这个简单的代码,但 CHrome 中显示了通知,而 checkPermission() 返回良好 0

我做了与此网站(示例)相同的操作,它在我的 Chrome 浏览器中运行良好。

if (window.webkitNotifications.checkPermission() == 0) {
  window.webkitNotifications.createNotification("icon.png", "title", "text").show();
} else {
  window.webkitNotifications.requestPermission();
}

问题出在哪里?

[编辑:问题已解决]

事实上,我允许在 Chrome 设置中显示来自所有网站的通知,现在,它工作正常!

enter image description here

最佳答案

请求权限仅适用于用户手势(请参阅下面的问题,并引用文档)。

简而言之,您需要注册一个点击事件或类似的事件然后请求权限。

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/

相关文章:

javascript - JQuery:创建图像和div,然后将图像附加到div

html - svg 虚线仅当鼠标悬停在路径上时才悬停

javascript - 如何同时激活按钮个人资料和帖子?

javascript - Chrome 在尝试流式传输 OGG 文件时终止响应

javascript - 在 Node js 中的 Socket.io 中为特定用户发出事件

javascript - ReactJs - 不可变地组合多个样式对象

Chrome 阻止了 Javascript 打印

html - 为什么我的标题不显示在某些浏览器上?

javascript - chrome setInterval() 对于模糊标签无法正常工作,即使是 1 秒或更长的时间

javascript - 如何打开包含浏览器信息的页面?