push-notification - 如何为推送通知添加分析

标签 push-notification service-worker web-push progressive-web-apps push-api

我正在开发渐进式网络应用程序,我想为推送通知实现分析。

如何为推送通知添加分析,以便我能够跟踪和记录有多少人点击了通知,以及有多少人在没有点击的情况下关闭了该通知。

最佳答案

我编写了一小段代码来使用谷歌分析进行分析,它运行得相当好。

在这里转储笔记:https://gauntface.com/blog/2016/05/01/push-debugging-analytics

我这样做的方式是上面提到的帖子:

在服务人员中,我导入了一个为我进行跟踪的 javascript 文件,设置分析 ID,然后在适当的事件中调用跟踪。寻找 self.analytics.trackEvent :

importScripts('./scripts/analytics.js');

self.analytics.trackingId = 'UA-77119321-2';

self.addEventListener('push', function(event) {
  let notificationTitle = 'Hello';
  const notificationOptions = {
    body: 'Thanks for sending this push msg.',
    icon: './images/icon-192x192.png',
    tag: 'simple-push-demo-notification'
  };

  // Important to trigger analytics asynchronously with logic
  // to show notification
  event.waitUntil(
    Promise.all([
      self.analytics.trackEvent('push-received'),
      self.registration.showNotification('Hello', notificationOptions)
    ])
  );
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();

  // Important to trigger analytics asynchronously with logic
  // to do other work (i.e. open window)
  event.waitUntil(
    Promise.all([
      self.analytics.trackEvent('notification-click'),
      clients.openWindow('https://gauntface.github.io/simple-push-demo/')
    ])
  );
});

对 Google Analytics Measurements Protocol 进行实际跟踪调用的代码如下所示。 API 非常简单,因此 payloadData 是分析期望的属性,我以 API 期望的格式生成这些参数的字符串,过滤掉空/空值:

class Analytics {
  trackEvent(eventAction, eventValue) {
    if (!this.trackingId) {
      console.error('You need to set a trackingId, for example:');
      console.error('self.analytics.trackingId = \'UA-XXXXXXXX-X\';');

      // We want this to be a safe method, so avoid throwing Unless
      // It's absolutely necessary.
      return Promise.resolve();
    }

    if (!eventAction && !eventValue) {
      console.warn('sendAnalyticsEvent() called with no eventAction or ' +
      'eventValue.');
      return Promise.resolve();
    }

    return self.registration.pushManager.getSubscription()
    .then(subscription => {
      if (subscription === null) {
        // The user has not subscribed yet.
        throw new Error('No subscription currently available.');
      }

      const payloadData = {
        // GA Version Number
        v: 1,
        // Client ID
        cid: subscription.endpoint,
        // Tracking ID
        tid: this.trackingId,
        // Hit Type
        t: 'event',
        // Data Source
        ds: 'serviceworker',
        // Event Category
        ec: 'serviceworker',
        // Event Action
        ea: eventAction,
        // Event Value
        ev: eventValue
      };

      const payloadString = Object.keys(payloadData)
      .filter(analyticsKey => {
        return payloadData[analyticsKey];
      })
      .map(analyticsKey => {
        return `${analyticsKey}=` +
          encodeURIComponent(payloadData[analyticsKey]);
      })
      .join('&');

      return fetch('https://www.google-analytics.com/collect', {
        method: 'post',
        body: payloadString
      });
    })
    .then(response => {
      if (!response.ok) {
        return response.text()
        .then(responseText => {
          throw new Error(
            `Bad response from Google Analytics ` +
            `[${response.status}] ${responseText}`);
        });
      }
    })
    .catch(err => {
      console.warn('Unable to send the analytics event', err);
    });
  }
}

if (typeof self !== 'undefined') {
  self.analytics = new Analytics();
}

您可以在以下网址找到所有这些:https://github.com/gauntface/simple-push-demo

关于push-notification - 如何为推送通知添加分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37452152/

相关文章:

javascript - 即使不在网站上,服务人员也会发送推送通知

firebase - 服务 worker 事件waitUntil()被传递了一个 promise ,但被 'TypeError: b is null'拒绝

electron - 是否可以在 Electron 应用程序中接收网络推送?

google-cloud-messaging - 使用 Pubnub 在渐进式 Web 应用程序上发送和接收推送通知

javascript - Chrome 推送通知(注册并等待通知)

使用 NodeJS 的 iOS 推送通知 - 凭据

objective-c - 关于 Google 文档文档更新的推送通知

android - IBM Worklight 5.0.6.1 - 手机/应用程序关闭时未收到推送通知

Android - 如果应用程序正在运行,停止(拦截)C2DM 推送通知?

reactjs - 为什么我的 create-react-app 没有服务人员?