gatsby - 将浏览量事件添加到谷歌标签管理器 + 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 });
解决方案
在您的组件/页面中使用useEffect
挂钩。AuseEffect
是在加载 DOM 树后触发的事件(类似于componentDidMount
、componentDidUpdate
和componentWillUnmount
生命周期的组合)。
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'
)时推荐的语句。window
document
推荐阅读
- git - 是否可以将代码推送到 bitbucket 到不存在的存储库中?
- android - 使用所需 Intent/Activity 时的 ViewModel 生命周期
- sql - 有什么方法可以让我做 ALIAS 引用其他列值?
- python - 我如何在另一个类中使用一个类的方法(是否可能)
- python - python3中是否需要区分方法和函数?
- ios - 在子 UIScrollView 之前触发 UIPanGestureRecognizer
- sql - 如何在 SQL Server 中通过 OPENROWSET 或 SomeFunction 选择动态字符串 SQL 结果
- java - 使用 gradle 分发插件中的 zip/tar
- r - R Plotly:带表格的子图
- openssl - 将 Godaddy 证书转换为 .pfx 文件