javascript - 放置 gtag 事件片段头 Gatsby/React 站点
问题描述
我在感谢页面上放置事件片段时遇到问题。该站点是用 GatsbyJS 构建的。我的想法是将事件片段放在使用 React 头盔中,但似乎无法弄清楚如何正确地做到这一点。我尝试了所有不同的方法,但似乎都没有:
<Helmet>
<script>
gtag('event', 'conversion', {'send_to': 'AW-MYID'});
</script>
</Helmet>
<Helmet>
<script
gtag('event', 'conversion', {'send_to': 'AW-MYID'});
/>
</Helmet>
<Helmet>
<script>
{`
gtag('event', 'conversion', {'send_to': 'AW-MYID'});
`}
</script>
</Helmet>
解决方案
根据gatsby-plugin-google-gtag
文档在服务器端渲染(SSR)中添加自定义事件:
typeof window !== "undefined" && window.gtag("event", "click", { ...data })
您需要先访问window
对象。当然,在检查它是否可用之后,如Gatsby 中的调试 HTML 显示的请求时间。
当然,这假设你已经在你的gatsby-config.js
. 理想的定制应如下所示:
plugins: [
{
resolve: `gatsby-plugin-google-gtag`,
options: {
// You can add multiple tracking ids and a pageview event will be fired for all of them.
trackingIds: [
"GA-TRACKING_ID", // Google Analytics / GA
"AW-CONVERSION_ID", // Google Ads / Adwords / AW
"DC-FLOODIGHT_ID", // Marketing Platform advertising products (Display & Video 360, Search Ads 360, and Campaign Manager)
],
// This object gets passed directly to the gtag config command
// This config will be shared across all trackingIds
gtagConfig: {
optimize_id: "OPT_CONTAINER_ID",
anonymize_ip: true,
cookie_expires: 0,
},
// This object is used for configuration specific to this plugin
pluginConfig: {
// Puts tracking script in the head instead of the body
head: false,
// Setting this parameter is also optional
respectDNT: true,
// Avoids sending pageview hits from custom paths
exclude: ["/preview/**", "/do-not-track/me/too/"],
},
},
},
],
推荐阅读
- c# - 没有文字转语音的 Nexmo 语音通话
- bazel - 从源文件路径派生 Bazel 标签
- python - 正则表达式在子字符串之前捕获所有内容
- python - Python Messenger Bot 仅适用于管理员,不适用于所有人
- git - Teamcity 仅从一个分支触发标签
- wordpress - Wordpress Multisite - API 帖子返回一个空数组
- rendering - HoloLens 外部渲染
- javascript - 在 React JS 中生成随机数
- .net - xUnit 单元测试项目未读取 App.config
- webpack - 无法加载“webpack”,它没有注册!也许您缺少一些插件?