'Blazor Web Assembly Push Notifications

I want to add Push notifications for the Blazor WebAssembly project. The only working example is in the Blazing Pizza project, but it does not work in the Net 5.0 version because the Service Worker is different.

If you just add

pushNotifications.js

when the application is launched for the first time, a request for the permission of push notifications appears, as it should be, but on the next launches, an error occurs:

RequestNotificationSubscriptionAsync: Unable to read the "PushManager"
property of an undefined blazor. 
webassembly.js:1 Type error: Unable to read the "PushManager" property of undefined.

The error occurs in then line:

const worker = await navigator.serviceWorker.getRegistration();

Maybe this is not the only problem of the script, but it is not yet clear why it is not possible to get SW registration on the next launches of the application

I will be grateful for any help

UPDATE

service-worker.js

self.addEventListener('fetch', () => { });

pushNotifications.js:

(function () {
        const applicationServerPublicKey = 'BKb...........................8';
    
        window.blazorPushNotifications = {
            requestSubscription: async () => {
                const worker = await navigator.serviceWorker.getRegistration();
                const existingSubscription = await worker.pushManager.getSubscription();
                if (!existingSubscription) {
                    const newSubscription = await subscribe(worker);
                    if (newSubscription) {
                        return {
                            url: newSubscription.endpoint,
                            p256dh: arrayBufferToBase64(newSubscription.getKey('p256dh')),
                            auth: arrayBufferToBase64(newSubscription.getKey('auth'))
                        };
                    }
                }
            }
        };
    
        async function subscribe(worker) {
            try {
                return await worker.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: applicationServerPublicKey
                });
            } catch (error) {
                if (error.name === 'NotAllowedError') {
                    return null;
                }
                throw error;
            }
        }
    
        function arrayBufferToBase64(buffer) {
            var binary = '';
            var bytes = new Uint8Array(buffer);
            var len = bytes.byteLength;
            for (var i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            return window.btoa(binary);
        }
    })();

There is also service-worker.published.js and I can't find anything about it...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source