我正在使用react-helmet
在特定页面上包含google tag manager脚本标签。它可以正常工作,但开玩笑会引发声明异常。
通常我会使用jest.mock
,但似乎无法为此工作,并且似乎也不会开玩笑地忽略该行代码。
<Helmet>
<title>{messages.title.defaultMessage}</title>
<meta name="title" content={messages.metaTitle.defaultMessage} />
<meta name="description" content={messages.metaDescriptions.defaultMessage} />
<meta name="keyword" content={messages.metaKeyword.defaultMessage} />
{/* Google Tag Manager */}
<script id="ga-script" type="text/javascript">
{((w, d, s, l, i) => {
w[l] = w[l] || [];
w[l].push({
'gtm.start': new Date().getTime(),
event: 'gtm.js',
});
const f = d.getElementsByTagName(s)[0];
const j = d.createElement(s);
const dl = l !== 'dataLayer' ? `&l=${l}` : '';
j.async = true;
j.src = `https://www.googletagmanager.com/gtm.js?id=${i}${dl}`;
f.parentNode.insertBefore(j, f);
f.className = 'ga-script';
j.className = 'ga-script';
})(window, document, 'script', 'dataLayer', 'GTM-000000')}
</script>
{/* End Google Tag Manager*/}
</Helmet>
<VerificationPhonePage /> equalEmailProps › encountered a declaration exception
TypeError: Cannot read property 'parentNode' of undefined
296 | j.async = true;
297 | j.src = `https://www.googletagmanager.com/gtm.js?id=${i}${dl}`;
> 298 | f.parentNode.insertBefore(j, f);
| ^
299 | f.className = 'ga-script';
300 | j.className = 'ga-script';
301 | })(window, document, 'script', 'dataLayer', 'GTM-000000')}
答案 0 :(得分:0)
我从没使用过Google跟踪代码管理器,但在我看来,此脚本在React上显得有些过分。
您可以这样做:
const i = 'GTM-000000'
// "i" is not self descriptive, rename it
// but if the value never change, insert it directly in url
const src = `https://www.googletagmanager.com/gtm.js?id=${i}`
// the only important code in your function
window.dataLayer = window.dataLayer || []
window.dataLayer.push({
'gtm.start': new Date().getTime(),
event: 'gtm.js',
})
<Helmet>
<script src={src} async className="ga-script" />
</Helmet>
答案 1 :(得分:0)
为了简单地模拟该方法,我通过以下方式获得了结果(我正在使用Vue和Jest):
Vue代码:
set PIDFile=%PATH_TO%\pid.txt
rem if the same file has been running, then kill it.
if exist "%PIDFile%" (
set /p targetPID=<%PIDFile%
taskkill /f /t /pid !targetPID!
del !PIDFile!
)
rem write this process ID down on the file so that other processces can read it.
powershell "Get-WmiObject win32_process -filter processid=$pid | ForEach-Object{$_.parentprocessid;}" >> %PATH_TO%\pid.txt
rem main process here
del !PIDfile!
笑话单位:
created(){
this.pushPageTitleInGTM()
},
methods:{
pushPageTitleInGTM(){
this.$gtm.trackEvent({
event: 'Page Title',
category: 'Page Title',
action: 'Page Load',
label: '404 Page',
value: '404',
pageTitle: '404',
});
}
}