'Show and hide a JavaScript snippet using a Google Tag Manager (GTM) custom event on a single page application (SPA)?

I am trying to setup Google Tag Manager (GTM) on my single page application (SPA).

I am pushing a custom datalayer event for each page view that looks like this:

window.dataLayer.push({
    event: 'customPageView',
    path: path,
    pageUrl: window.location.href,
    pageTitle: document.title,
    pageReferrer: pageReferrer,
    requiresAuth: requiresAuth,
    cid: getCid(),
  });

And I am using the requiresAuth value to conditionally show a JavaScript snippet from Zoho Desk. When the Zoho Desk JavaScript snippet is present it should display a floating help icon on the page for the user to interact with.

I only want the snippet to load on internal pages where requiresAuth = true. All of the login pages have requiresAuth = false and I do not want the snippet to load there.

Inside GTM I have a Tag that fires when the customPageView event has requiresAuth = true. Here is a screenshot of the Trigger:

enter image description here

When first visiting the app it seems to work fine.

The login page does not show the floating Zoho Desk icon because on that page requiresAuth = false.

After logging in the floating Zoho Desk icon appears because all of those pages have requiresAuth = true.

But then I logout and get redirected back to the login page and the Zoho Desk icon is still showing. It does not disapear until I refresh the page.

It should have disappeared as soon as I was redirected to the login page because it has requiresAuth = false.

How do I fix this?

When debugging with GTM Preview feature everything looks correct - yet it still doesn't work.

Zoho Desk Tag on login page first visit:

enter image description here

Zoho Desk Tag on internal page visits:

enter image description here

Zoho Desk Tag on login page after I logout:

enter image description here

As you can see from the screenshots above, the tag is firing and not firing correctly. Yet I can still see the Zoho Desk icon after logging out (unless I refresh the page, then it correctly disapears).



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source