0

I want to open a new page on notification click in my Flutter web app. Here is my service worker:

console.log("SW: test.js loaded");

self.addEventListener("push", event => {
  console.log("SW: Push event received:", event);

  let data = {};
  try {
    data = event.data ? event.data.json() : {};
  } catch (err) {
    console.warn("SW: Push data not JSON, using empty object");
  }

  const title = data.title || "Test Push Title";
  const options = {
    body: data.body || "This notification came from the push event.",
    icon: "/icons/icon-192.png",
    tag: "push-demo",
    data: {
      url: "/"
    }
  };

  console.log("SW: Showing notification:", title, options);

  event.waitUntil(
    self.registration.showNotification(title, options)
  );
});

self.addEventListener("notificationclick", event => {
  console.log("SW: Notification clicked event:", event);

  event.notification.close();

  const url = event.notification.data.url || "/";

  event.waitUntil(
    clients.openWindow(url)
  );
});

And this is where I register the service worker:

<script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function () {
        navigator.serviceWorker.register('test.js').then(reg => {
          console.log("SW registered:", reg);
        }).catch(err => {
          console.error("SW failed:", err);
        });
      });
    }
</script>

The problem is that when I run my application on the localhost, the notification is displayed, but the click callback is not fired. Here is console output in debug build:

 SW: test.js loaded
test.js:4 SW: Push event received: PushEvent {isTrusted: true, data: PushMessageData, type: 'push', target: ServiceWorkerGlobalScope, currentTarget: ServiceWorkerGlobalScope, …}
test.js:10 SW: Push data not JSON, using empty object
(anonymous) @ test.js:10
test.js:23 SW: Showing notification: Test Push Title {body: 'This notification came from the push event.', icon: '/icons/icon-192.png', tag: 'push-demo', data: {…}}

In the release build, everything works fine. How can I test notificationclick event in the debug build?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.