如何使用Chrome桌面通知?我想在我自己的代码中使用它。

更新:这里有一篇博文用一个例子解释了webkit通知。


当前回答

<!DOCTYPE html>

<html>

<head>
<title>Hello!</title>
<script>
function notify(){

if (Notification.permission !== "granted") {
Notification.requestPermission();
}
 else{
var notification = new Notification('hello', {
  body: "Hey there!",
});
notification.onclick = function () {
  window.open("http://google.com");
};
}
}
</script>
</head>

<body>
<button onclick="notify()">Notify</button>
</body>

其他回答

<!DOCTYPE html>

<html>

<head>
<title>Hello!</title>
<script>
function notify(){

if (Notification.permission !== "granted") {
Notification.requestPermission();
}
 else{
var notification = new Notification('hello', {
  body: "Hey there!",
});
notification.onclick = function () {
  window.open("http://google.com");
};
}
}
</script>
</head>

<body>
<button onclick="notify()">Notify</button>
</body>

检查设计和API规范(它仍然是草稿)或从(页面不再可用)查看一个简单的例子的源代码:它主要是对window.webkitNotifications.createNotification的调用。

如果你想要一个更健壮的例子(你试图创建自己的谷歌Chrome的扩展,并想知道如何处理权限,本地存储等),检查Gmail Notifier扩展:下载crx文件而不是安装它,解压缩它并阅读其源代码。

这里有关于api的很好的文档,

https://developer.chrome.com/apps/notifications

谷歌的官方视频解释,

https://developers.google.com/live/shows/83992232-1001

我喜欢:http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples,但它使用旧的变量,所以演示不再工作。webkitNotifications现在是Notification。

请参见ServiceWorkerRegistration.showNotification

这似乎是一个窗口。webkitNotifications已经被弃用并删除。然而,有一个新的API,它似乎也可以在最新版本的Firefox中工作。

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}`);
  }
}

codepen