Introduction to the Notification API
The Notifications API is the interface that browsers expose to the developer to allow showing messages to the user, with their permission, even if the web site / web app is not open in the browser.
Those messages are consistent and native, which means that the receiving person is used to the UI and UX of them, being system-wide and not specific to your site.
In combination with the Push API this technology can be a successful way to increase user engagement and to enhance the capabilities of your app.
The Notifications API interacts heavily with Service Workers, as they are required for Push Notifications. You can use the Notifications API without Push, but its use cases are limited.
if (window.Notification && Notification.permission !== "denied") {
Notification.requestPermission((status) => {
// status is "granted", if accepted by user
var n = new Notification('Title', {
body: 'I am the body text!',
icon: '/path/to/icon.png' // optional
})
})
}
n.close()
Permissions
To show a notification to the user, you must have permission to do so.
The Notification.requestPermission()
method call requests this permission.
You can call
Notification.requestPermission()
in this very simple form, and it will show a permission permission granting panel - unless permission was already granted before.
To do something when the user interacts (allows or denies), you can attach a processing function to it:
const process = (permission) => {
if (permission === "granted") {
// ok we can show the permission
}
}
Notification.requestPermission((permission) => {
process(permission)
}).then((permission) => {
process(permission)
})
See how we pass in a callback and also we expect a promise. This is because of different implementations of Notification.requestPermission()
made in the past, which we now must support as we don’t know in advance which version is running in the browser. So to keep things in a single location I extracted the permission processing in the process()
function.
In both cases that function is passed a permission
string which can have one of these values:
granted
: the user accepted, we can show a permissiondenied
: the user denied, we can’t show any permission
Those values can also be retrieved checking the Notification.permission
property, which - if the user already granted permissions - evaluates to granted
or denied
, but if you haven’t called Notification.requestPermission()
yet, it will resolve to default
.
Create a notification
The Notification
object exposed by the window
object in the browser allows you to create a notification and to customize its appearance.
Here is the simplest example, that works after you asked for permissions:
Notification.requestPermission()
new Notification('Hey')
You have a few options to customize the notification.
Add a body
First, you can add a body, which is usually shown as a single line:
new Notification('Hey', {
body: 'You should see this!'
})
Add an image
You can add an icon property:
new Notification('Hey', {
body: 'You should see this!',
icon: '/user/themes/writesoftware/favicon.ico'
})
More customization options, with platform-specific properties, can be found at https://developer.mozilla.org/docs/Web/API/Notification
Close a notification
You might want to close a notification once you opened it.
To do so, create a reference to the notification you open:
const n = new Notification('Hey')
and then you can close it later, using:
n.close()
or with a timeout:
setTimeout(n.close(), 1 * 1000)
Download my free JavaScript Beginner's Handbook
More browser tutorials:
- Some useful tricks available in HTML5
- How I made a CMS-based website work offline
- The Complete Guide to Progressive Web Apps
- The Fetch API
- The Push API Guide
- The Channel Messaging API
- Service Workers Tutorial
- The Cache API Guide
- The Notification API Guide
- Dive into IndexedDB
- The Selectors API: querySelector and querySelectorAll
- Efficiently load JavaScript with defer and async
- The Document Object Model (DOM)
- The Web Storage API: local storage and session storage
- Learn how HTTP Cookies work
- The History API
- The WebP Image Format
- XMLHttpRequest (XHR)
- An in-depth SVG tutorial
- What are Data URLs
- Roadmap to learn the Web Platform
- CORS, Cross-Origin Resource Sharing
- Web Workers
- The requestAnimationFrame() guide
- What is the Doctype
- Working with the DevTools Console and the Console API
- The Speech Synthesis API
- How to wait for the DOM ready event in plain JavaScript
- How to add a class to a DOM element
- How to loop over DOM elements from querySelectorAll
- How to remove a class from a DOM element
- How to check if a DOM element has a class
- How to change a DOM node value
- How to add a click event to a list of DOM elements returned from querySelectorAll
- WebRTC, the Real Time Web API
- How to get the scroll position of an element in JavaScript
- How to replace a DOM element
- How to only accept images in an input file field
- Why use a preview version of a browser?
- The Blob Object
- The File Object
- The FileReader Object
- The FileList Object
- ArrayBuffer
- ArrayBufferView
- The URL Object
- Typed Arrays
- The DataView Object
- The BroadcastChannel API
- The Streams API
- The FormData Object
- The Navigator Object
- How to use the Geolocation API
- How to use getUserMedia()
- How to use the Drag and Drop API
- How to work with scrolling on Web Pages
- Handling forms in JavaScript
- Keyboard events
- Mouse events
- Touch events
- How to remove all children from a DOM element
- How to create an HTML attribute using vanilla Javascript
- How to check if a checkbox is checked using JavaScript?
- How to copy to the clipboard using JavaScript
- How to disable a button using JavaScript
- How to make a page editable in the browser
- How to get query string values in JavaScript with URLSearchParams
- How to remove all CSS from a page at once
- How to use insertAdjacentHTML
- Safari, warn before quitting
- How to add an image to the DOM using JavaScript
- How to reset a form
- How to use Google Fonts