7

Trying to achieve content grouping in mobile site which is SPA.

The scenario goes like this: When I am visiting a PDP page for the first time, category variable is set and this is sent to content groups in Universal Analytics Tag. If after this I go back to the homepage, the category variable doesn't update and homepage is also grouped under the same content group of previous PDP page.

This variable only updates when I visit another PDP page.

I am using a custom event PageLoad to mimic the pageView event. Just want the data layer varaibles to refresh within the consecutive PageLoad event.

Thanks

Pranay
  • 121
  • 1
  • 2
  • 7
  • Did you try to update that variable for every pageview? – mrbubu Apr 28 '17 at 20:46
  • Yes thats what I am looking for .... but not sure how to do it. Can this be done via firing a Tag through GTM using dataLayer.push – Pranay May 01 '17 at 10:03
  • Yes, it can be done with custom HTML tag. But it is much better to push data to dataLayer from backend. – mrbubu May 03 '17 at 18:51

3 Answers3

5

There is now a documented way to reset the data layer. See Reset in the Data layer docs.

If you push a function to the dataLayer, it'll give you access to an object with get, set, and reset semantics. For this question in particular, reset is the relevant bit.

Matt Hamrick
  • 759
  • 5
  • 10
  • I have to say, this is more than perfect. It amazing, thanks for this. This is specially useful when dealing with many variables – jtomasrl Mar 04 '21 at 12:07
4

If the reset() doesn't work for you, maybe you want to try the following code

const boomDataLayer = () => {
  if (window.dataLayer !== undefined && window.google_tag_manager !== undefined) {
    window.dataLayer.length = 0;
    const gtmContainerReg = /GTM-/i;

    for (const gtmKey of Object.keys(window.google_tag_manager)) {
      if (gtmContainerReg.test(gtmKey) && window.google_tag_manager[gtmKey].dataLayer
        && window.google_tag_manager[gtmKey].dataLayer.reset
      ) {
        window.google_tag_manager[gtmKey].dataLayer.reset();
      }
    }
  }
}
lazurey
  • 307
  • 3
  • 9
  • 1
    Not sure why https://developers.google.com/tag-platform/devguides/datalayer#reset did not work. This one worked. – Benedikt Feb 01 '23 at 13:31
3

There's an undocumented way to cleanup the whole dataLayer using this method:

var gtm = window.google_tag_manager['GTM-XXXXXX'];
gtm.dataLayer.reset();

Now you don't necessarily need to do that since you can set the values you don't want anymore to undefined in your dataLayer:

dataLayer.push({
  'please_go_away': undefined
});
cheesemacfly
  • 11,622
  • 11
  • 53
  • 72