Home > Web Front-end > JS Tutorial > How Do Desktop Notifications Work in Chrome?

How Do Desktop Notifications Work in Chrome?

DDD
Release: 2024-11-03 22:21:02
Original
653 people have browsed it

How Do Desktop Notifications Work in Chrome?

Chrome Desktop Notifications Explained

Desktop notifications in modern browsers enable the display of simple messages on the screen. They're particularly useful when you want to alert or inform users even when they're not interacting with your website.

There are two types of notifications:

Desktop Notifications:

  • Easy to display
  • Automatically disappear after a few seconds
  • Available only while the web page is open

Service Worker Notifications:

  • More complex to implement
  • Can be persistent and appear even when the web page is closed
  • Support action buttons

Accessing the Desktop Notification API:

The Desktop Notification API uses similar parameters for both types, as documented on MDN. To access this API:

  1. Request permission on page load.
  2. Create a new Notification object with a title, icon, and body text.
  3. Assign an event listener to handle actions (onclick).

Example Implementation:

<code class="js">document.addEventListener('DOMContentLoaded', function() {
  if (!Notification) alert('Desktop notifications not available in your browser.');
  if (Notification.permission !== 'granted') Notification.requestPermission();
});

function notifyMe() {
  if (Notification.permission === 'granted') {
    var notification = new Notification('Notification title', {
      icon: 'icon.png',
      body: 'Hey there! You\'ve been notified!',
    });
    notification.onclick = function() {
      window.open('http://example.com');
    };
  } else Notification.requestPermission();
}</code>
Copy after login

HTML:

<code class="html"><button onclick="notifyMe()">Notify me!</button></code>
Copy after login

The above is the detailed content of How Do Desktop Notifications Work in Chrome?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template