首页 > 解决方案 > 将浏览量事件添加到谷歌标签管理器 + gatsby

问题描述

我正在尝试将自定义数据层片段 (dataLayer.push(❴'event': “pageview”❵)) 添加到 Gatbsy GTM 插件。我该怎么做?有人帮忙吗?

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ originalLocation: document.location.protocol + '//' + document.location.hostname + document.location.pathname + document.location.search });

标签: gatsbygatsby-plugin

解决方案


在您的组件/页面中使用useEffect挂钩。AuseEffect是在加载 DOM 树后触发的事件(类似于componentDidMountcomponentDidUpdatecomponentWillUnmount生命周期的组合)。

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (typeof window !== 'undefined'){
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ originalLocation: document.location.protocol + '//' + document.location.hostname + document.location.pathname + document.location.search });
    }
  }, []);

  return (
    <div>
      <p>Your page</p>
    </div>
  );
}

注意条件,这是在服务器端渲染中处理全局对象(例如typeof window !== 'undefined')时推荐的语句。windowdocument


推荐阅读