Home > Web Front-end > JS Tutorial > How to Implement Desktop Notifications in Modern Browsers?

How to Implement Desktop Notifications in Modern Browsers?

Susan Sarandon
Release: 2024-11-04 04:39:29
Original
417 people have browsed it

How to Implement Desktop Notifications in Modern Browsers?

Chrome desktop notification example

Two types of notifications exist in modern browsers:

  • Desktop Notifications - easy to trigger, active as long as the page is open, and may automatically disappear after a few seconds.
  • Service Worker Notifications - A bit complex, but they work in the background (even after the page is closed), are persistent and support action buttons.

API calls take the same parameters (except for actions - not available in desktop notifications), which are well documented on MDN and, for service workers, on Google's Web Fundamentals site .

Here is a working example of a desktop notification for Chrome, Firefox, Opera and Safari. Note that for security reasons, starting with Chrome 62, notification API permissions may no longer be requested from the cross-origin framework, so we cannot demonstrate this using a code snippet from StackOverflow. You need to save this example in the HTML file of your website/application and make sure to use localhost:// or HTTPS.

<code class="js">// 在页面加载时请求权限
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');
  };
 }
}</code>
Copy after login
<code class="html"><button onclick="notifyMe()">Notify me!</button></code>
Copy after login

The above is the detailed content of How to Implement Desktop Notifications in Modern Browsers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template