Skip to content

No active Service Worker Error #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
SethuSenthil opened this issue May 15, 2018 · 9 comments
Open

No active Service Worker Error #1

SethuSenthil opened this issue May 15, 2018 · 9 comments

Comments

@SethuSenthil
Copy link

Hi! I really appreciate your youtube video on how to use push notifications with node. But I'm having an issue on client.js line 6 (where it catches errors, so line # is not that helpful)
Error:
DOMException: Subscription failed - no active Service Worker

I believe the service worker is not registered so it can proceed any further. I also tried downloading the code straight from the repo and I'm still getting this error. Thanks in advance!

@ralscha
Copy link

ralscha commented May 16, 2018

It looks like that the method register.pushManager.subscribe requires an active service worker.
The first time you open the page the method navigator.serviceWorker.register installs the service worker, the code waits for the asynchronous install phase but after that the activation phase is running asynchronous too.

You can wait for the service worker to become active with the ready property

// Register Service Worker
  console.log("Registering service worker...");
  const register = await navigator.serviceWorker.register("/worker.js", {
    scope: "/"
  });
  console.log("Service Worker Registered...");

  await navigator.serviceWorker.ready;  // <---------- WAIT 
  
  // Register Push
  console.log("Registering Push...");
  const subscription = await register.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(publicSigningKey)
  });
  console.log("Push Registered...");

@mindfulme
Copy link

Try changing your vapid keys, as shown in the video (I suggest generate your own pair).

@khwilo
Copy link

khwilo commented May 4, 2020

@ralscha great explanation on the solution. I had also encountered the same problem that @SethuSenthil had.

@lukasvdberk
Copy link

@ralscha legend!

@thanhhiep206
Copy link

i use your code but when i run , i have a bug 'DOMException: Registration failed - permission denied'

@ralscha
Copy link

ralscha commented Jan 21, 2022

@dth2k1 Did you block notification for this URL? Chrome: Open Settings, search for "site settings", open Site Settings, scroll down to Permissions, click on Notifications. There you find a list of all URLs you blocked.

@aditodkar
Copy link

It looks like that the method register.pushManager.subscribe requires an active service worker. The first time you open the page the method navigator.serviceWorker.register installs the service worker, the code waits for the asynchronous install phase but after that the activation phase is running asynchronous too.

You can wait for the service worker to become active with the ready property

// Register Service Worker
  console.log("Registering service worker...");
  const register = await navigator.serviceWorker.register("/worker.js", {
    scope: "/"
  });
  console.log("Service Worker Registered...");

  await navigator.serviceWorker.ready;  // <---------- WAIT 
  
  // Register Push
  console.log("Registering Push...");
  const subscription = await register.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(publicSigningKey)
  });
  console.log("Push Registered...");

I tried it but did not work for me

@ralscha
Copy link

ralscha commented May 31, 2022

@aditodkar What error do you get?

@aditodkar
Copy link

aditodkar commented May 31, 2022

@aditodkar What error do you get?

In my case register.pushManager.subscribe is never fulfilled I tried to wrap it inside try/catch block but does not throw any error. Same thing happened https://stackoverflow.com/questions/46633866/reg-pushmanager-subscribe-is-never-fulfilled But after clearing cache and making some code changes I was able to resolve it.
Working code:

function urlBase64ToUint8Array(base64String) {
    var padding = '='.repeat((4 - base64String.length % 4) % 4);
    var base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    var rawData = window.atob(base64);
    var outputArray = new Uint8Array(rawData.length);

    for (var i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}

async function subscribeUserToPush() {
    try {
        const registration = await navigator.serviceWorker.register('/sw.js')
        console.log("registration", registration)

        const subscribeOptions = {
            userVisibleOnly: true,
            applicationServerKey: urlBase64ToUint8Array('KEY'),
        };

        const pushSubscription = await registration.pushManager.subscribe(subscribeOptions);
        console.log(
            'Received PushSubscription: ',
            JSON.stringify(pushSubscription),
        );
    } catch (error) {
        console.log("e", error)
    }
}

async function init() {
    console.log("init")
    try {
        if (!('serviceWorker' in navigator)) {
            // Service Worker isn't supported on this browser, disable or hide UI.
            return;
        }

        if (!('PushManager' in window)) {
            // Push isn't supported on this browser, disable or hide UI.
            return;
        }

        const premission = await Notification.requestPermission();
        console.log("premission", premission)

        if (premission === 'granted') {

            await subscribeUserToPush()

        }
    } catch (error) {
        console.log("error", error)
    }
}

(async () => {
    await init()
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants