最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Notification not received by poling method set interval. on PWA using service workers - Stack Overflow

programmeradmin3浏览0评论

Here in my code when accessed on a PWA(Ipad in my example) the API call is made successfully also the PWA asks for notification permissions but after that there is no notification received on the PWA

this is my code of where im checking for notifications on regular intervals

const checkForAlerts = async () => {
    try {
        console.log(`Checking for alerts at: with client`); // Add logging
        // alert(`Checking for alerts at: with client`);

        const response = await client.post("/api/alert-notification", {});

        if (response.status) {
            console.log("New Alerts:", response.data);
            alert("API call successful");

            if (!("Notification" in window)) {
                alert("This browser does not support desktop notification");
            } else if (Notification.permission === "granted") {
                alert("permission granted ");
                response.data.data.forEach((alert: any) => {
                    new Notification("New Alert", {
                        body: alert.message,
                        icon: "/icons/bell.svg",
                    });
                });
                alert("notif made ");
            } else if (Notification.permission !== "denied") {
                Notification.requestPermission().then((permission) => {
                    if (permission === "granted") {
                        response.data.data.forEach((alert: any) => {
                            new Notification("New Alert", {
                                body: alert.message,
                                icon: "/icons/bell.svg",
                            });
                        });
                    }
                });
            } else if (Notification.permission !== "denied") {
                Notification.requestPermission().then((permission) => {
                    if (permission === "granted") {
                        response.data.data.forEach((alert: any) => {
                            new Notification("New Alert", {
                                body: alert.message,
                                icon: "/icons/bell.svg",
                            });
                        });
                    }
                });
            }
        }
    } catch (error) {
        console.error("Error checking for alerts:", error);
        alert(`Error checking for alerts: ${JSON.stringify(error)}`);
        console.error("Error details:", error);
    }
};

// Set up polling once logged in, skip login route
useEffect(() => {
    if (window.location.pathname !== "/") {
        // alert("im here in useEffect");
        const intervalId = setInterval(checkForAlerts, 3000); // 5 minutes interval
        // Cleanup the interval on unmount or if navigating to login page
        return () => clearInterval(intervalId);
    }
}, []);

======================================================================================

This is my Service worker

const urlsToCache = ["/","/index.html","/manifest.json",];

self.addEventListener("install", (event) => {event.waitUntil(caches.open(CACHE_NAME).then((cache) => {return cache.addAll(urlsToCache);}));});

self.addEventListener("fetch", (event) => {event.respondWith(caches.match(event.request).then((response) => {return response || fetch(event.request).catch((error) => {console.error('Fetch failed:', error);throw error;});}));});

// Push event handlerself.addEventListener("push", (event) => {alert("alert recieved")

let notificationData = event.data ? event.data.json() : {};

const options = {body: notificationData.message || "New alert!",icon: "/icon.png",badge: "/badge.png",};

alert("alert recieved")

// Show the notificationevent.waitUntil(self.registration.showNotification(notificationData.title || "Alert", options));});

// Handle click on notificationself.addEventListener("notificationclick", (event) => {event.notification.close(); // Close the notification

const notificationData = event.notification.data || {};

event.waitUntil(clients.openWindow(notificationData.url || "/dashboard"));});

====================================================================================== This is my manifest file

{
    "short_name": "Test App",
    "name": "Test App",
    "icons": [
      {
        "src": "favicon.ico",
        "sizes": "64x64 32x32 24x24 16x16",
        "type": "image/x-icon"
      },
      {
        "src": "logo192.png",
        "type": "image/png",
        "sizes": "192x192"
      },
      {
        "src": "logo512.png",
        "type": "image/png",
        "sizes": "512x512",
        "purpose": "any maskable"
      }
    ],
    "description": "Your app description",
    "start_url": "/",
    "display": "standalone",
    "theme_color": "#000000",
    "background_color": "#ffffff"
  }
  

The API call is successful, the service worker is registered, the permission is granted form the PWA for notification also in safari advanced option in settings PUSH API is also enabled

发布评论

评论列表(0)

  1. 暂无评论