0

我目前在我的代码中使用 Facebook Pixel 来处理事件重复数据删除。所有初始化和跟踪功能都已成功发送并登录到 Facebook。

但是当我使用 next-pwa 创建 PWA 时,Facebook Pixel 出错了。Facebook Pixel 事件仅在 Hard Reload (Ctrl + F5) 时触发,但当我刷新页面或重新访问页面时,Facebook Pixel 不会被触发。我使用 Facebook Pixel Helper 来注意事件是否被触发。

通过查看网络选项卡和 Workbox 控制台日志,我注意到 Workbox 可能会拦截对 Facebook 的请求。 用于添加到购物车的 Facebook 网络选项卡的 Workbox 日志

我注入 Facebook Pixel Script 的代码:

export const InjectFBQ = (
  f?: any,
  b?: any,
  e?: any,
  v?: any,
  n?: any,
  t?: any,
  s?: any
) => {
  if (!f.fbq && typeof window !== 'undefined') {
    n = f.fbq = function () {
      n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
    };
    if (!f._fbq) f._fbq = n;
    n.push = n;
    n.loaded = !0;
    n.version = '2.0';
    n.queue = [];
    t = b.createElement(e);
    t.async = !0;
    t.src = v;
    s = b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t, s);
  }
};

export const InitializeFBQ = (pixelID: string) => {
  if (typeof window !== 'undefined') {
    window.fbq('init', pixelID);
    window.fbq.disablePushState = true;
    window.fbq.allowDuplicatePageViews = true;
  }
};

然后在我的 index.js 中,我使用 useEffect Hook 调用它。请注意,PixelID 是从 GraphQL 获取的:

    useEffect(() => {
      if (typeof window !== 'undefined' && PixelID) {
        if (
          !localStorage.getItem('PixelID') ||
          localStorage.getItem('PixelID') === undefined
        ) {
          localStorage.setItem('PixelID', PixelID);
        }
      }
      
      if(typeof window !== 'undefined'){
        InjectFBQ(
          typeof window !== 'undefined' && window,
          typeof window !== 'undefined' && document,
          'script',
          'https://connect.facebook.net/en_US/fbevents.js'
        );
        InitializeFBQ(PixelID)
      }

    }, [PixelID]);

我的 next.config.js

const withPWA = require('next-pwa');

module.exports = withPWA({
  target: 'server',
  pwa: {
    dest: 'public',
    // disable: process.env.NODE_ENV === 'development',
    maximumFileSizeToCacheInBytes: 10000000,
  },
})

我尝试在每次重新加载页面时初始化 Facebook Pixel,但不幸的是它不起作用。我认为这与 Workbox 如何处理第三方请求有关。已经阅读了处理来自 Google 的第三方请求,但仍然无法正常工作。对此有什么帮助吗?

谢谢!

4

0 回答 0