elgorditosalsero / react-gtm-hook

Easily manage the Google Tag Manager via Hook
https://elgorditosalsero-react-gtm-hook.netlify.app/
MIT License
220 stars 28 forks source link

Missing possibility to disable GTM connection #80

Open MerzDaniel opened 1 year ago

MerzDaniel commented 1 year ago

Background We'd like to be able to conditionally disable the GTM data collection (e.g. Based on user consent or feature switch). However, there is no API for that. This is important due to GDPR legislation which requires explicit user approval before any data collection is happening.

Feature Request Extend the GtmProvider with a prop enabled that prevents all communication with Google in case it is false

const Providers = ({ children }) => (
  <GTMProvider state={{
    id,
    environment,
    enabled=isGtmEnabled()
   }}> {children} </GTMProvider>
)

Workarounds we tried As we couldn't find an API to disable GTM, we tried the following workarounds:

duy-the-developer commented 11 months ago

Hi @MerzDaniel, I know it's been a couple of months since your issue was opened, but did you manage to find a solution? If not, you could try setting injectScript to false. This should prevent the GTM script injection on first load and allow you to enable it later in your flow while still mounting the Provider. Similar to what was mentioned in issue #30.

Something like this:

const Providers = ({ children }) => (
  <GTMProvider state={{
    id,
    environment,
    injectScript: false // --> prevent script injection
   }}> {children} </GTMProvider>
)

Then later once the user accepted Cookies:

const Consumer = () => {
  const sendDataToGTM = useGTMDispatch()
  if (cookiesAccepted) sendDataToGTM({ injectScript: true}) 
  // more code here...
}

Disclaimer: I'm not a maintainer but looking at the source code this in theory should work.