首页 > 解决方案 > 如何在 Service Worker 中使用 ApplicationInsights-JS?

问题描述

我目前在我的渐进式 Web 应用程序中使用 ApplicationInsights-JS。它适用于我的反应组件,因为我可以从相关的 npm 包中导入我需要的内容。

然而,在我的服务工作者中,我只能使用 importScripts 导入逻辑。

我确实设法在他们的 Github 页面上找到了 ApplicationInsights-JS 的 CDN,但是似乎为了使用此库初始化应用程序洞察力,您需要访问窗口以存储 appinsights,而您无法从服务人员那里做到这一点.

我尝试使用网络片段方法,因为 CDN 似乎与该特定库相关,但我不能使用 window 并且不确定如何实现此解决方案。

这是建议片段的复制粘贴,用于从以下位置初始化应用洞察对象:https ://github.com/Microsoft/ApplicationInsights-JS

importScripts('https://az416426.vo.msecnd.net/beta/ai.2.min.js');

const sdkInstance = 'appInsightsSDK';
window[sdkInstance] = 'appInsights';
const aiName = window[sdkInstance];

const aisdk =
  window[aiName] ||
  (function(e) {
    function n(e) {
      i[e] = function() {
        const n = arguments;
        i.queue.push(function() {
          i[e](...n);
        });
      };
    }
    let i = { config: e };
    i.initialize = !0;
    const a = document;

    const t = window;
    setTimeout(function() {
      const n = a.createElement('script');
      (n.src = e.url || 'https://az416426.vo.msecnd.net/next/ai.2.min.js'),
        a.getElementsByTagName('script')[0].parentNode.appendChild(n);
    });
    try {
      i.cookie = a.cookie;
    } catch (e) {}
    (i.queue = []), (i.version = 2);
    for (
      const r = [
        'Event',
        'PageView',
        'Exception',
        'Trace',
        'DependencyData',
        'Metric',
        'PageViewPerformance'
      ];
      r.length;

    )
      n(`track${r.pop()}`);
    n('startTrackPage'), n('stopTrackPage');
    const o = `Track${r[0]}`;
    if (
      (n(`start${o}`),
      n(`stop${o}`),
      !(
        !0 === e.disableExceptionTracking ||
        (e.extensionConfig &&
          e.extensionConfig.ApplicationInsightsAnalytics &&
          !0 ===
            e.extensionConfig.ApplicationInsightsAnalytics
              .disableExceptionTracking)
      ))
    ) {
      n(`_${(r = 'onerror')}`);
      const s = t[r];
      (t[r] = function(e, n, a, t, o) {
        const c = s && s(e, n, a, t, o);
        return (
          !0 !== c &&
            i[`_${r}`]({
              message: e,
              url: n,
              lineNumber: a,
              columnNumber: t,
              error: o
            }),
          c
        );
      }),
        (e.autoExceptionInstrumented = !0);
    }
    return i;
  })({ instrumentationKey: 'xxx-xxx-xxx-xxx-xxx' });
(window[aiName] = aisdk),
  aisdk.queue && aisdk.queue.length === 0 && aisdk.trackPageView({});

我得到 window is not defined 这是预期的,但我不确定我还能如何从服务人员那里使用这个库。

有没有其他人有类似的实现,他们使用来自服务工作者的 ApplicationInsights 成功记录遥测数据?

标签: reactjsservice-workerazure-application-insightsweb-worker

解决方案


我意识到我把这件事复杂化了。

由于我只需要跟踪自定义事件,并且不需要 appInsights 所做的所有自动页面跟踪等,因此我最终从我的服务人员那里进行了获取。

我只是从使用我的反应页面发出的请求中复制了标题和正文格式。

以下成功将遥测记录到我的应用洞察仪表板:

fetch(url, {
  method: 'post',
  headers: {
    'Content-type': 'application/json'
  },
  body: JSON.stringify([
    {
      time: '2019-05-02T15:56:37.589Z',
      iKey: 'INSTRUMENTATION_KEY',
      name:
        'Microsoft.ApplicationInsights.INSTRUMENTATION_KEY.Event',
      tags: {
        'ai.user.id': 'l6Tey',
        'ai.session.id': 'TL+Ry',
        'ai.device.id': 'browser',
        'ai.device.type': 'Browser',
        'ai.operation.id': 'HUfNE',
        SampleRate: '100',
        // eslint-disable-next-line no-script-url
        'ai.internal.sdkVersion': 'javascript:2.0.0-rc4'
      },
      data: {
        baseType: 'EventData',
        baseData: {
          ver: 2,
          name: 'Testing manual event',
          properties: {},
          measurements: {}
        }
      }
    }
  ])
})
  .then(json)
  .then(function(data) {
  })
  .catch(function(error) {
  });

推荐阅读