I'm trying to setup up web notifications with FCM and I get error messages when trying to register the service worker.
My structure is as follows:
domain.com/notification/index.html
domain.com/notification/test-worker.js
Index.html:
function registerServiceWorker()
{
console.log('start register');
return navigator.serviceWorker.register('/notification/test-worker.js')
.then(function(registration)
{
console.log('Service worker successfully registered.');
askPermission();
return registration;
})
.catch(function(err)
{
console.error('Unable to register service worker.', err);
});
console.log('end register');
}
test-worker.js
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-analytics.js";
const messaging = getMessaging();
onBackgroundMessage(messaging, (payload) => {
console.log(' Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.'
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
The errors I get are:
Uncaught SyntaxError: Cannot use import statement outside a module
Unable to register service worker. TypeError: Failed to register a ServiceWorker for scope ('https://example.com/notification/') with script ('https://example.com/notification/test-worker.js'): ServiceWorker script evaluation failed
I understand that import cannot be used outside of a module but how can I specify that the service worker should be a module? I have seen many examples of service workers using import so I guess it should be possible to use import. Or should I use a different method?
Thanks
I fought with this same issue for a while. Lots of searching, trial and error later. I figured out that you have to register your service worker as a module.
navigator.serviceWorker.register('/firebase-messaging-sw.js', { type: 'module' });
After that you should be able to call the import from your file.
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