I want to try sending notifications from a web page to desktop or mobile, but mobile requires service-worker.js to work. So can I use it? service-worker.js for my website?
You should be able to.
Just try it and see if it works! It’s not against the ToS or anything, so feel free to experiment
Make sure js file is below 1MB
I’ll try later.
Before that, can the service-worker.js really fix this?
TypeError: Failed to construct ‘Notification’: Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead.
## scrip.js ##
var notification;
function showNotification() {
notification = new Notification('$nama_pengirim', {
body: '$pesan_notifikasi'
});
notification.onclick = function(event) {
event.preventDefault();
window.location.href = '$url';
};
}
if (Notification.permission === 'granted') {
showNotification();
} else {
Notification.requestPermission().then(function(permission) {
if (permission === 'granted') {
showNotification();
}
});
}
service-worker.js
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(
clients.openWindow(event.notification.data.url)
);
});
script on index
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Service Worker registered:', registration);
})
.catch(function(error) {
console.error('Service Worker registration failed:', error);
});
});
}
I think it should
It seems the reasoning for deprecating the Notification() constructor is that a site may be closed before the notification is created/sent. Therefore, it makes more sense to send it from the service worker.
Again, give it a try to see if it works! The worst that can happen is that it doesn’t work.
Sorry, turns out I had to make some changes, and it worked
Thank you to all of you
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.