I have a web application. I want to use the HTML 5 inbuilt notifications API to do push notifications from the server when the user is on a particular page. Is it possible?
The API call from your back-end / application that triggers a push message to a user's device. The service worker JavaScript file that will receive a "push event" when the push arrives on the device. It's in this JavaScript that you'll be able to show a notification.
Write a function showNotification(options) that creates a notification: <div class="notification"> with the given content. The notification should automatically disappear after 1.5 seconds. Use CSS positioning to show the element at given top/right coordinates.
Many believe push notifications are primarily a mobile app feature, but push notifications can also be used with web apps through a browser. As a result, businesses are starting to realize that web app notifications are just as beneficial as mobile.
You can do real push notifications with Web apps today in Chrome using Service Workers and PushManager from the W3C Push API.
See the article Push Notifications on the Open Web for a step-by-step how-to and code snippets you can use. Here’s a diagram from that article that explains what the UI around it looks like.
An implementation of the Push API has already landed in Firefox too; it’s targeted for shipping in November 2015 in Firefox 42. And Microsoft has indicated that the Push API is also under consideration for implementation in Edge team as well.
Below is a simple code example, borrowed from MDN.
this.onpush = function(event) {
console.log(event.data);
}
navigator.serviceWorker.register('serviceworker.js').then(
function(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe().then(
function(pushSubscription) {
console.log(pushSubscription.subscriptionId);
console.log(pushSubscription.endpoint);
}, function(error) {
console.log(error);
}
);
}
);
It depends on what you want to achieve:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With