lea*_*ner 6 google-tag-manager reactjs
我正在尝试用reactjs实现GTM.我使用了react-google-tag-manager,但它没有解决目的.不知何故,数据层需要采用特定的格式,并且需要在标签的正下方,但它只是我一次可以实现的其中之一.我尝试将代码直接放在template.html中,并从我想要的组件调用该函数,但这不起作用.
import React from 'react';
import gtmParts from 'react-google-tag-manager';
class GoogleTagManager extends React.Component {
componentDidMount() {
const dataLayerName = this.props.dataLayerName || 'dataLayer';
const scriptId = this.props.scriptId || 'react-google-tag-manager-gtm';
if (!window[dataLayerName]) {
const gtmScriptNode = document.getElementById(scriptId);
eval(gtmScriptNode.textContent);
}
}
render() {
const gtm = gtmParts({
id: this.props.gtmId,
sourcegroup: this.props.gtmGroupname,
sourceid:this.props.gtmSource,
age:this.props.age,
mtongue:this.props.gtmMtongue,
city:this.props.city,
});
return (
<div>
<div>{gtm.noScriptAsReact()}</div>
<div id={this.props.scriptId || 'react-google-tag-manager-gtm'}>
{gtm.scriptAsReact()}
</div>
</div>
);
}
}
export default GoogleTagManager;
Run Code Online (Sandbox Code Playgroud)
我在DataLayer中推送参数并检查google tag assistant addon,整个数据表是空的.
昨天我遇到了这个问题,为了解决这个问题,我不得不将要记录的所有属性都放在该属性下additionalEvents。像这样:
const gtm = gtmParts({
id: this.props.gtmId,
additionalEvents: {
sourcegroup: this.props.gtmGroupname,
sourceid:this.props.gtmSource,
age:this.props.age,
mtongue:this.props.gtmMtongue,
city:this.props.city
}
})
Run Code Online (Sandbox Code Playgroud)
并避免使用,eval()因为这是危险的做法。像这样更新您的代码:
if (!window[dataLayerName]) {
const script = document.createElement("script")
const gtmScriptNode = document.getElementById(scriptId)
const scriptText = document.createTextNode(gtmScriptNode.textContent)
script.appendChild(scriptText)
document.head.appendChild(script)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6289 次 |
| 最近记录: |