Skip to content

injectScript as init param possible? #1

@TheWalkingDad3

Description

@TheWalkingDad3

Hi acomanescu,
first of all, thank you very much for the fork and the react 19 support.

I am missing a feature from the "old" lib - with the condition injectScript it was possible to dynamically decide if the GTM Script should be injected or not. The use case is for example when a cookie banner has to be confirmed before gtm is allowed to be included.

Is there any other possibility to achieve this goal or do you plan to add such a feature?

With the old library we did it this way

function App({ Component, pageProps }: AppProps) {
  const [injectScript, setInjectScript] = useState(false);
  useEffect(() => {
    if (typeof window !== 'undefined' && !window.OptanonWrapper) {
      window.OptanonWrapper = () => {
        window.OneTrust.OnConsentChanged(() => {
          if (window.OptanonActiveGroups.indexOf('C0002') > -1) {
            setInjectScript(true);
          }
        });
      };
    }
    if (
      typeof window !== 'undefined' &&
      document.cookie.replace(/(?:(?:^|.*;\s*)OptanonConsent\s*=\s*([^;]*).*$)|^.*$/, '$1').indexOf('C0002') > -1
    ) {
      setInjectScript(true);
    }
  }, []);

  return (
    <GTMProvider state={{ injectScript, ...gtmParams }}>
      <Component {...pageProps} />
    </GTMProvider>
  );
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions