javascript - Gatsbyjs + Google 分析 - 跟踪自定义事件?
问题描述
是否有可能使用 gatsby 和谷歌分析来跟踪自定义事件?
解决方案
我已经将ReactGA与 Gatsby 结合使用并取得了很好的成功。
对于基本的事件跟踪——比如记录点击的链接——它非常容易使用。您在组件中创建一个日志记录函数,该函数访问ReactGA.event
然后在您的渲染函数中使用onClick
.
记录 PDF 下载的示例组件:
import React from 'react'
import Link from 'gatsby-link'
import ReactGA from 'react-ga'
import logo from './logo.png'
import financials from './Annual_Report_Financials_2017_FINAL.pdf'
class LoggingDownload extends React.Component {
logger() {
// Detect each click of the financial PDF
ReactGA.event({
category: 'Financial Download',
action: 'User clicked link to view financials'
})
}
render() {
return (
<div>
<nav className="nav-container">
<Link to="/locations">
<img className="logo" src={logo} alt="Logo" />
</Link>
<ul className="nav-item-container">
<li className="nav-item">
<a href="/shortsignup/" target="_blank">Join Us</a>
</li>
<li className="nav-item">
<a href={financials} onClick={this.logger} target="_blank" id="financials-pdf">Financials</a>
</li>
</ul>
</nav>
</div>
)
}
}
export default LoggingDownload
还有很多用例——查看 ReactGA 文档。
另外:不要忘记ggatsby-plugin-google-analytics
在您的gatsby-config.js
文件中包含作为使上述内容正常工作的依赖项:
{
resolve: `gatsby-plugin-google-analytics`,
options: {
trackingId: "UA-#########-##",
// Puts tracking script in the head instead of the body
head: false,
// Setting this parameter is optional
respectDNT: true,
}
}
推荐阅读
- python - 两个总和问题 - Python。请解释解决方案,对我来说没有意义
- java - 使用stream api java计算嵌套元素的数量
- python - 与客户端断开连接时出现 Aiohttp 服务器严重错误
- python - Python OSError [ErrNo22] PyPDF2 脚本
- javascript - 如何使用我指定的端口运行我的图像?
- python - 为什么我的 Python mysql 类 __init__ 函数试图重载 mysql 包 __init__ 函数?
- javascript - Protobuf 编码返回空值
- javascript - 当 URL 包含特定术语时显示/隐藏元素
- python - mypy:disallow_any_unimported 未按预期工作
- angular - 为角度桌面应用程序设置量角器 e2e