Skip to content

Instantly share code, notes, and snippets.

@jikanter
Forked from cougrimes/lib-singlepageapp.js
Last active December 6, 2023 04:05
Show Gist options
  • Select an option

  • Save jikanter/c31af9fafe3925ddd565913540a3ddbf to your computer and use it in GitHub Desktop.

Select an option

Save jikanter/c31af9fafe3925ddd565913540a3ddbf to your computer and use it in GitHub Desktop.
[DL Data Layer Workaround] Utag singlepageapp.js #datalayer
/* Welcome to lib-singlepageapp.js! This script is meant to handle using single-page
applications (SPAs) for Tealium when you do not have direct access to Angular, Vue,
React, etc. for making modifications. This allows us to get around limitations of
utag.view(). The trigger in this case is a global event listener that evaluates
any time there is a click. If a new URL is populated via the history API, we'll treat
that as a "pageview". Note in this case that I have defined a UDO variable of page.
This variable is then mapped to anything requiring a page URL. For example, in GA I
have this variable mapped to config.page_location so it acts like a native page URL view.*/
/*
I got frustrated by the lack of more intuitive single-page app tracking in Tealium and wrote a hacky workaround. Use at your own discretion.
*/
//Set up our utag configuration to treat everything as noview until we tell it otherwise
window.utag_cfg_ovrd = window.utag_cfg_ovrd || {};
window.utag_cfg_ovrd.noview = true;
// Listen for changes on the URL itself once there is a click as our trigger for recording "pageviews".
let url = location.href;
document.body.addEventListener('click', () => {
requestAnimationFrame(() => {
url !== location.href && utag.view({
"page": document.URL
});
url = location.href;
});
}, true);
/* TODO: Add Mutation Observer code so that other changes to content are supported */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment