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

next.js - Clevertab Push Notification Not Visible Despite Successful Event Received - Stack Overflow

programmeradmin3浏览0评论

I have integrated CleverTap Web SDK in our Next.js project to capture user events and display push notifications. While we can see that the push event is received successfully, the notification itself does not appear in the UI. There are no explicit errors preventing it from showing, but it remains invisible.

Environment

  • OS: Mac Os M1
  • Browser: Chrome 133.0.6943.99
  • CleverTap Web SDK Version: 1.11.12
  • Next.js Version: 12.3.4

service worker(clevetab_sw.js)

      !(function (n) {
        'function' == typeof define && define.amd ? define(n) : n();
      })(function () {
        'use strict';
        if (
          (importScripts(
            '.min.js'
          ),
          void 0 === t)
        )
          var n, t;
        function i(n, t, i) {
          let e = '',
            c = t;
          'action1' === n.action
            ? (void 0 !== i.notificationOptions.actions[0].deepLink &&
                ((c +=
                  '&r=' +
                  encodeURIComponent(i.notificationOptions.actions[0].deepLink)),
                (e = i.notificationOptions.actions[0].deepLink)),
              (c += '&b=' + encodeURIComponent('button1')))
            : 'action2' === n.action
            ? (void 0 !== i.notificationOptions.actions[1].deepLink &&
                ((c +=
                  '&r=' +
                  encodeURIComponent(i.notificationOptions.actions[1].deepLink)),
                (e = i.notificationOptions.actions[1].deepLink)),
              (c += '&b=' + encodeURIComponent('button2')))
            : (void 0 !== i.deepLink &&
                ((c += '&r=' + encodeURIComponent(i.deepLink)), (e = i.deepLink)),
              (c += '&b=' + encodeURIComponent('button0'))),
            o(c),
            e && clients.openWindow(e),
            n.notification.close();
        }
        self.addEventListener('install', function (n) {
          self.skipWaiting(), console.log('CT Service worker installed');
        }),
          self.addEventListener('activate', function (n) {
            console.log('CT Service worker activated');
          }),
          self.addEventListener('push', function (i) {
            console.log('Push event received', i.data.text());
            if (!i.data) {
              console.error('Push event received but no data!');
              return;
            }
            var o,
              e = JSON.parse(i.data.text()),
              c = e.title || 'CleverTap',
              a = e.notificationOptions,
              d = a.data;
            void 0 !== d &&
              ((d.wzrk_id += '_'.concat(new Date().getTime())), (o = d.wzrk_id)),
              void 0 === o && (o = c),
              localforage
                .setItem(o, i.data.text())
                .then(function (n) {})
                .catch(function (n) {
                  console.log('Error in persisting');
                }),
              (t = e.redirectPath),
              (n = e);
            var s = e.raiseNotificationViewedPath;
            void 0 !== s && fetch(s, { mode: 'no-cors' }),
              i.waitUntil(
                self.registration
                  .showNotification(c, a)
                  .then(() => console.log('Notification Showed'))
                  .catch((err) => {
                    console.error('Notification Error:', err);
                  })
              );
          }),
          self.addEventListener('notificationclick', function (o) {
            var e,
              c = o.notification,
              a = c.data;
            null != a && (e = a.wzrk_id), void 0 === e && (e = c.title);
            var d = localforage
              .getItem(e)
              .then(function (n) {
                var t = JSON.parse(n),
                  e = t.redirectPath;
                i(o, e, t);
              })
              .catch(function (e) {
                i(o, t, n), console.log(e);
              });
            o.waitUntil(d);
          });
        var o = function (n) {
          fetch((n += '&s=true'), { mode: 'no-cors' });
        };
      });

my clevertab hook (useClevertab.ts)

    import CleverTap from 'clevertap-web-sdk/clevertap';
    import { useCallback, useEffect, useState } from 'react';

    import { clevertabEventMapping } from '../utils/constants';
    import { getUserFromLocal } from '../utils/localstorage';

    const CLEVERTAP_ACCOUNT_ID = process.env
      .NEXT_PUBLIC_CLEVERTAB_PROJECT_ID as string;

    export const useCleverTap = () => {
      const [clevertapModule, setClevertapModule] = useState<CleverTap>();

      const clevertapInit = useCallback(async () => {
        if (!clevertapModule) {
          const module = await initializeClevertap();
          setClevertapModule(module);
        }
      }, [clevertapModule]);

      useEffect(() => {
        clevertapInit();
      }, [clevertapInit]);

      const initializeClevertap = async (): Promise<CleverTap> => {
        const clevertapModule = await import('clevertap-web-sdk');
        clevertapModule.default.init(CLEVERTAP_ACCOUNT_ID);
        clevertapModule.default.privacy.push({ optOut: false });
        clevertapModule.default.privacy.push({ useIP: false });
        clevertapModule.default.setLogLevel(3);

        return clevertapModule.default;
      };

      const trackEventOnClevertab = (
        eventName: string,
        payload: Record<string, any> = {}
      ) => {
        if (clevertapModule) {
          if (
            eventName === clevertabEventMapping.signIn ||
            eventName === clevertabEventMapping.login
          ) {
            payload = {
              Name: `${payload?.firstName} ${payload?.lastName}`,
              Identity: payload?.email,
              Phone: payload?.mobile?.replace('-', ''),
              id: payload?.id,
              isVerified: !!payload?.isVerfied,
              language: payload?.language,
              profileImage: payload?.profileImage,
              status: !!payload?.status,
              email: payload?.email,
              userAddress: payload?.userAddress?.address,
              country: payload?.country?.code,
            };
          }
          payload['userType'] = getUserFromLocal() ? 'authenticated' : 'guest';
          payload['timestamp'] = new Date().toISOString();
          clevertapModule.event.push(eventName, payload);
        }
      };

      const captureUserOnClevertab = (user: Record<string, any>) => {
        if (!clevertapModule) {
          console.warn('CleverTap is not initialized yet.');
          return;
        }
        clevertapModule.onUserLogin.push({
          Site: {
            Name: `${user?.firstName} ${user?.lastName}`,
            Identity: user?.email,
            Phone: user?.mobile?.replace('-', ''),
            id: user?.id,
            isVerified: !!user?.isVerfied,
            language: user?.language,
            profileImage: user?.profileImage,
            status: !!user?.status,
            email: user?.email,
            userAddress: user?.userAddress?.address,
            country: user?.country?.code,
          },
        });
        askUserNotifications();
      };

      const askUserNotifications = () => {
        if (!clevertapModule) {
          console.warn('CleverTap is not initialized yet.');
          return;
        }
        clevertapModule.notifications.push({
          titleText: 'Would you like to receive Push Notifications?',
          bodyText: 'We promise to only send you relevant content',
          okButtonText: 'Allow',
          rejectButtonText: 'No thanks',
          okButtonColor: '#F28046',
          askAgainTimeInSeconds: 5,
          serviceWorkerPath: '/clevertap_sw.js',
        });
        console.log('Notification perimissiion asked');
      };

      return {
        trackEventOnClevertab,
        captureUserOnClevertab,
        askUserNotifications,
      };
    };

I tried all the steps mentioned in their documentation for web push.

发布评论

评论列表(0)

  1. 暂无评论