Home > Web Front-end > JS Tutorial > How to Show Desktop Notifications in Chrome?

How to Show Desktop Notifications in Chrome?

Patricia Arquette
Release: 2024-11-03 04:52:03
Original
661 people have browsed it

How to Show Desktop Notifications in Chrome?

How to Implement Desktop Notifications in Chrome?

Modern browsers offer two notification types: desktop notifications and service worker notifications. Desktop notifications are simpler to trigger, functioning only while the page is open and potentially disappearing after a short interval.

The API call for both types takes identical parameters (except for actions, which are unavailable for desktop notifications).

Desktop Notification Example for Chrome

The below code snippet demonstrates desktop notifications in Chrome:

<code class="javascript">// 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 to display a notification
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

HTML to Trigger Notification

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

The above is the detailed content of How to Show Desktop Notifications 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template