Home >Web Front-end >JS Tutorial >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>
HTML to Trigger Notification
<code class="html"><button onclick="notifyMe()">Notify me!</button></code>
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!