We're managing a chat plugin using GTM, in our Next.js application.
We want everything to be managed via GTM, no code on the FE. So GTM takes care of injecting the main script and then GTM takes also care of injecting the init script.
We'd like the chat to be visible only on certain pages, but not others.
Problem. Once loaded, the script is loaded.
Right now it was implemented statically, and that's the reason it doesn't work as expected:
<script>
window.addEventListener("foo", () => {
// DO SOMETHING
});
</script>
So of course once loaded, the callback will fire on every page.
My idea to do this dynamically, would be using dynamic variables, something like this
<script>
const enableFoo = {{customGTMVariable}};
</script>
<script>
enableFoo && window.addEventListener("foo", () => {
// DO SOMETHING
});
</script>
Can this work or should I go for something using the DataLayer?
I'm not a GTM expert, but our consultants theoretically are. I want to be prepared when I talk to them in order to address the issue.
Maybe a cookie can be updated at every page change?
The important thing is not touching the FE code. What can be done with GTM can be done.
The solution is