![](/img/trans.png)
[英]Difficulty installing Google Tag Manager in React for Google Analytics
[英]Google Analytics ga('set') equivalant on Google Tag Manager
引自https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
当您的应用程序动态加载内容并更新地址栏中的 URL 时,存储在您的跟踪器上的数据也应该更新。
ga('set', 'page', '/new-page.html');
如果我将 Google Tag Manager 与 Google Analytics 一起使用,我该如何运行它?
下面是我如何使用高阶组件在 React 路由器上更改路由时跟踪网页浏览的片段
componentDidMount() {
const { history } = this.props;
this.history = history.listen(location => {
if (history.action === 'PUSH') {
// location change
if (window && window.dataLayer) {
const dataLayer = window.dataLayer || [];
const { pathname, search } = location;
// how to achieve this with Google Tag Manager?
// ga.set('page', `${pathname}${search}`);
setTimeout(() => {
dataLayer.push({
event: 'Pageview',
});
}, 1000);
}
}
});
}
如果您使用的是 GTM,那么我可以推荐两个选项。
选项 1,如果您的应用实际更新 URL 作为路由更改:
创建一个新的 GA 标签并确保选中“在此标签中启用覆盖设置”,然后在底部有“更多设置”的下拉菜单,您将看到“要设置的字段”,单击“添加字段”并您可以添加“页面”并将值设置为 {{Page Path}}。 然后添加在步骤 1 中创建的触发器
保存并运行,您应该会通过此事件向 GA 发送综合浏览量数据。 路径将是浏览器 url 栏中的任何内容。
如果您想要一个更加自定义的路径,那么您可以将您的代码修改为以下内容,我们将“page-path”变量添加到数据层。
componentDidMount() {
const { history } = this.props;
this.history = history.listen(location => {
if (history.action === 'PUSH') {
// location change
if (window && window.dataLayer) {
const dataLayer = window.dataLayer || [];
const { pathname, search } = location;
// how to achieve this with Google Tag Manager?
// ga.set('page', `${pathname}${search}`);
setTimeout(() => {
dataLayer.push({
page-path: ${pathname}${search},
event: 'Pageview'
});
}, 1000);
}
}
});
}
然后你需要设置一个新的数据层变量来在 GTM 中捕获它:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.