Explain Codes LogoExplain Codes Logo

Chrome desktop notification example

javascript
prompt-engineering
web-development
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 21, 2024
TLDR

Initiate a Chrome desktop notification by first seeking user permission and later dispatching it. Here is a clear-cut approach:

if (Notification.permission === "granted") { new Notification("New message!"); } else if (Notification.permission !== "denied") { Notification.requestPermission(permission => { // You won't believe what happens next... if (permission === "granted") new Notification("New message!"); }); } // no user=no chat bot=profit ?? :D

You must call this within a user-generated event, like a click, because Chrome respects the user's peace.

Checking and requesting permission

Prior to sounding the alarm, remember to verify the user's permission status. Save the user's response using local storage to avoid pestering them with constant requests.

if (!localStorage.getItem('notification-permitted')) { Notification.requestPermission().then(permission => { localStorage.setItem('notification-permitted', permission); }); // Hide and seek – the 2.0 digital version } // If they say no it means no, respect that!

In scenarios where notifications can't live without user permission, use apt UX/UI to give them a soft push – describe how notifications could light up their world.

Using service workers

Service Workers are taking over desktop notifications in the web development realm. They work off-screen and are highly persistent, despite needing the same user consent as their desktop siblings.

To tap into your notifications’ potential with service workers, ensure the user’s browser is wearing the compatibility badge. Then, enroll a Service Worker:

if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js'); // Drafting him into the notification army! }

Beyond this, Google's well-documented Web Fundamentals prepares you for a deep-dive into Service Worker notifications.

Managing notifications – Dos and don’ts

While deploying your notification brigade, keep the front-line browser compatibility in mind. Online platforms such as caniuse.com are great, a crystal globe showing how different browsers react to your notification API.

Keep notifications rich and engaging with titles, bodies, unique icons, and user interaction handlers. For that push across multiple browsers, libraries like notify.js can be your cavalry, introducing a host of fallbacks for the old guard.

new Notification('Breaking News', { body: 'Your subscription is expiring faster than a lighted fuse.', icon: '/path/to/icon.png', // A picture is worth 100 notifications onclick: function(event) { window.open('https://example.com'); // clicking got real } });

The Notification API – Unlocking mysteries

Localize your permission request to avoid surprising the user with an unfamiliar language. This API is a living organism that is constantly evolving – as seen in Chrome 62, which disallows Notification requests from cross-origin iframes.

Let's manage the Notification API transition from the retired window.webkitNotifications:

if ('Notification' in window) { // The new kid on the block } else if ('webkitNotifications' in window) { // The older folk still got it! } // Adapting faster than a chameleon on a disco floor!

The latest Notification API standard is your regular go-to for recent changes.

Distribute far and wide – cross-browser support

When your notifications have to reach out to different browsers like Firefox or Opera, evolve your code to match them. The nifty notify.js library could also work on Internet Explorer and Microsoft Edge, although you might wish to put that to a test.

// Creating a notification for different browsers - one ring to rule them all! function createNotification(title, options) { if (window.Notification) { return new Notification(title, options); } else if (window.webkitNotifications) { return window.webkitNotifications.createNotification( options.icon, title, options.body ); } else { // A different path for those who wander off } }