React SPA - GTM Analytics React-Helmet Previous Page Title

微笑、不失礼 提交于 2021-02-18 17:46:06

问题


I am using Google Tag Manager to push pageview events to the datalayer for Analytics tracking. This is happening in componentDidMount() (and sometimes componentWillReceiveProps() if I am listening for query string parameter changes with the location prop using withRouter).

I am using react-helmet to dynamically update my title and other tags as components change.

I have noticed an issue that I am getting the improper page title in Analytics. It's frequently showing the page title of the previous page, instead of the one I am currently on. It appears that react-helmet is not updating the tag until after componentDidMount().

Page View Event Function Example

My analytics tag in GTM is called every time this event is pushed to the data layer

const firePageViewEvent = () => {
      console.log("Pageview event fired (from tracking script)");

      if (window && window.dataLayer) {
          console.log("window and dataLayer exist, pushing pageview event.");
          let dataLayer = window.dataLayer || [];
          dataLayer.push({
              'event': 'reactPageViewEvent'
          });
      } else {
          console.log("window or dataLater does not exist, cannot push pageview event.");
      }
};

回答1:


I can confirm that wrapping the function in a setTimeOut() function with a 0ms delay does indeed work to ensure that the event is only pushed after react-helmet has a chance to do its thing.

This allows me to consistently get the current page title in Analytics.

See github issue comment

Updated Function

const firePageViewEvent = () => {
    setTimeout(() => {
        console.log("Pageview event fired (from tracking script)");

        if (window && window.dataLayer) {
            console.log("window and dataLayer exist, pushing pageview event.");
            let dataLayer = window.dataLayer || [];
            dataLayer.push({
                'event': 'reactPageViewEvent'
            });
        } else {
            console.log("window or dataLater does not exist, cannot push pageview event.");
        }
    }, 0);
};


来源:https://stackoverflow.com/questions/49322314/react-spa-gtm-analytics-react-helmet-previous-page-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!