admin管理员组文章数量:1391981
I have an app which has GTM tracking. I'm currently checking when a route has taken place and pushing a page_view event to the dataLayer.
The problem I'm having is getting the dataLayer to push when the app loads initially. I have a back button which when clicked goes back to the home screen and fires an event but I can't get it to fire when the app loads initially. I can explicitly add the push event to the home ponent when it mounts, which will work but when I click the go back button it will fire twice.
Here's my code does anyone know how to get this to work when the app loads initially without duplicating the push?
ponentDidUpdate(prevProps) {
if (this.props.path !== prevProps.path)
{
this.routeChange();
}
}
routeChange(){
window.dataLayer.push({
event: "page_view",
url: this.props.path
});
}
I have an app which has GTM tracking. I'm currently checking when a route has taken place and pushing a page_view event to the dataLayer.
The problem I'm having is getting the dataLayer to push when the app loads initially. I have a back button which when clicked goes back to the home screen and fires an event but I can't get it to fire when the app loads initially. I can explicitly add the push event to the home ponent when it mounts, which will work but when I click the go back button it will fire twice.
Here's my code does anyone know how to get this to work when the app loads initially without duplicating the push?
ponentDidUpdate(prevProps) {
if (this.props.path !== prevProps.path)
{
this.routeChange();
}
}
routeChange(){
window.dataLayer.push({
event: "page_view",
url: this.props.path
});
}
Share
Improve this question
edited Jul 17, 2018 at 10:06
Tholle
113k22 gold badges208 silver badges197 bronze badges
asked Jul 17, 2018 at 9:19
user3486427user3486427
4841 gold badge11 silver badges21 bronze badges
1 Answer
Reset to default 3You could create your history
object manually outside of the Router
and listen to changes on that and also send an event directly when the file loads.
Example
import createBrowserHistory from "history/createBrowserHistory";
const history = createBrowserHistory();
history.listen(location => {
const { pathname } = location;
window.dataLayer.push({
event: "page_view",
url: pathname
});
});
window.dataLayer.push({
event: "page_view",
url: window.location.pathname
});
function App() {
return (
<Router history={history}>
{/* ... */}
</Router>
);
}
本文标签: javascriptPush to dataLayer on initial app load ReactjsStack Overflow
版权声明:本文标题:javascript - Push to dataLayer on initial app load Reactjs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744707565a2620932.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论