Javascript Chrome 桌面通知示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2271156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:33:01  来源:igfitidea点击:

Chrome desktop notification example

javascriptdesktopgoogle-chromenotifications

提问by Sridhar Ratnakumar

How does one use Chrome desktop notifications? I'd like that use that in my own code.

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

Update: Here's a blog postexplaining webkit notifications with an example.

更新:这是一篇用示例解释 webkit 通知的博客文章

回答by Dan Dascalescu

In modern browsers, there are two types of notifications:

在现代浏览器中,有两种类型的通知:

  • Desktop notifications- simple to trigger, work as long as the page is open, and may disappear automatically after a few seconds
  • Service Worker notifications- a bit more complicated, but they can work in the background (even after the page is closed), are persistent, and support action buttons
  • 桌面通知- 触发简单,只要页面打开就可以工作,几秒钟后可能会自动消失
  • Service Worker 通知——有点复杂,但它们可以在后台工作(即使在页面关闭后),是持久的,并且支持操作按钮

The API call takes the same parameters (except for actions - not available on desktop notifications), which are well-documented on MDNand for service workers, on Google's Web Fundamentalssite.

API 调用采用相同的参数(除了操作 - 在桌面通知上不可用),这些参数在MDN和服务工作者以及Google 的 Web Fundamentals站点上都有详细记录。



Below is a working example of desktopnotifications for Chrome, Firefox, Opera and Safari. Note that for security reasons, starting with Chrome 62, permission for the Notification API may no longer be requested from a cross-origin iframe, so we can't demo this using StackOverflow's code snippets. You'll need to save this example in an HTML file on your site/application, and make sure to use localhost://or HTTPS.

下面是Chrome、Firefox、Opera 和 Safari桌面通知的工作示例。请注意,出于安全原因,从 Chrome 62 开始,可能不再从跨域 iframe 请求通知 API 的权限,因此我们无法使用 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>

We're using the W3C NotificationsAPI. Do not confuse this with the Chrome extensionsnotifications API, which is different. Chrome extension notifications obviously only work in Chrome extensions, and don't require any special permission from the user.

我们正在使用W3C 通知API。不要将此与Chrome扩展通知 API混淆,后者是不同的。Chrome 扩展程序通知显然只适用于 Chrome 扩展程序,不需要用户的任何特殊许可。

W3C notifications work in many browsers (see support on caniuse), and require user permission. As a best practice, don't ask for this permission right off the bat. Explain to the user first why they would want notificationsand see other push notifications patterns.

W3C 通知适用于许多浏览器(请参阅caniuse 上的支持),并且需要用户许可。作为最佳实践,不要立即请求此许可。首先向用户解释他们为什么需要通知并查看其他推送通知模式

Note that Chrome doesn't honor the notification icon on Linux, due to this bug.

请注意,由于此错误,Chrome 不支持 Linux 上的通知图标。

Final words

最后的话

Notification support has been in continuous flux, with various APIs being deprecated over the last years. If you're curious, check the previous edits of this answer to see what used to work in Chrome, and to learn the story of rich HTML notifications.

通知支持一直在不断变化,在过去几年中,各种 API 被弃用。如果您很好奇,请查看此答案的先前编辑以了解过去在 Chrome 中工作的内容,并了解富 HTML 通知的故事。

Now the latest standard is at https://notifications.spec.whatwg.org/.

现在最新的标准是在https://notifications.spec.whatwg.org/

As to why there are two different calls to the same effect, depending on whether you're in a service worker or not - see this ticket I filed while I worked at Google.

至于为什么有两个不同的调用具有相同的效果,这取决于您是否在服务工作者中 - 请参阅我在 Google 工作时提交的这张票

See also notify.jsfor a helper library.

另请参阅notify.js以获取帮助程序库。

回答by GmonC

Check the designand API specification(it's still a draft) or check the source from (page no longer available) for a simple example: It's mainly a call to window.webkitNotifications.createNotification.

检查设计API 规范(它仍然是一个草案)或检查来自(页面不再可用)的源代码以获取一个简单示例:主要是对window.webkitNotifications.createNotification.

If you want a more robust example (you're trying to create your own Google Chrome's extension, and would like to know how to deal with permissions, local storage and such), check out Gmail Notifier Extension: download the crx file instead of installing it, unzip it and read its source code.

如果您想要一个更强大的示例(您正在尝试创建自己的 Google Chrome 扩展程序,并且想知道如何处理权限、本地存储等),请查看Gmail 通知程序扩展程序:下载 crx 文件而不是安装它,解压缩并阅读其源代码。

回答by mpen

It appears that window.webkitNotificationshas already been deprecated and removed. However, there's a new API, and it appears to work in the latest version of Firefox as well.

似乎window.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

代码笔

回答by Rudie

I like: http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examplesbut it uses old variables, so the demo doesn't work anymore. webkitNotificationsis now Notification.

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

回答by gravmatt

I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.

我制作了这个简单的通知包装器。它适用于 Chrome、Safari 和 Firefox。

Probably on Opera, IE and Edge as well but I haven't tested it yet.

可能也适用于 Opera、IE 和 Edge,但我还没有测试过。

Just get the notify.js file from here https://github.com/gravmatt/js-notifyand put it into your page.

只需从这里获取 notify.js 文件https://github.com/gravmatt/js-notify并将其放入您的页面。

Get it on Bower

在 Bower 上获取

$ bower install js-notify

This is how it works:

这是它的工作原理:

notify('title', {
    body: 'Notification Text',
    icon: 'path/to/image.png',
    onclick: function(e) {}, // e -> Notification object
    onclose: function(e) {},
    ondenied: function(e) {}
  });

You have to set the title but the json object as the second argument is optional.

您必须设置标题,但作为第二个参数的 json 对象是可选的。

回答by Hina Halani

<!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>

回答by Ashley Davis

Notify.js is a wrapper around the new webkit notifications. It works pretty well.

Notify.js 是新的 webkit 通知的包装器。它工作得很好。

http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/

http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/

回答by Altaf Patel

Here is nice documentation on APIs,

这是关于 API 的很好的文档,

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

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

And, official video explanation by Google,

而且,谷歌官方视频解释,

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

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