Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: window.gtag is not a function

I'm totally puzzled with GTM, I implemented it to my webSite to trigger some events to handle traffic, ect... It's be like 2 days I saw the following error :

Error from the trackerPageView =>  TypeError: window.gtag is not a function
    at _app.js:1
    at _app.js:1
    at commons.c57c1be722ad069a7405.js:1
    at Array.map (<anonymous>)
    at Object.emit (commons.c57c1be722ad069a7405.js:1)
    at commons.c57c1be722ad069a7405.js:1

I didn't see any doc about this problem so I make a post to centralize information about this problem.

My config is a webApp (nextjs, Reactjs, typeScript, redux), hopefully this will help.

_document.tsx :

import Document, { Head, Main, NextScript } from "next/document";
import { GA_TRACKING_ID } from "../lib/gtag";
import { Fragment } from "react";

export default class MyDocument extends Document {
  setGoogleTags() {
    return {
      __html: `
            (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${GA_TRACKING_ID}');
          `,
    };
  }

  render() {
    return (
      <html lang="fr">
        <Head>
          <Fragment>
            <script dangerouslySetInnerHTML={this.setGoogleTags()} />
          </Fragment>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <meta name="theme-color" content="#000000" />
          <link
            rel="shortcut icon"
            href="***"
            crossOrigin="anonymous"
          />
          <link
            rel="stylesheet"
            href="***.css"
            crossOrigin="anonymous"
          />
        </Head>
        <body>
          <noscript>
            <iframe
              src={`https://www.googletagmanager.com/ns.html?id=${GA_TRACKING_ID}`}
              height="0"
              width="0"
              style={{ display: "none", visibility: "hidden" }}
            ></iframe>
          </noscript>
          <Main />
          <NextScript />
          <script
            type="text/javascript"
            id="hs-script-loader"
            async
            defer
            src="//js.hs-scripts.com/*****.js"
          ></script>
        </body>
      </html>
    );
  }
}

gtg/index.ts:

export const GA_TRACKING_ID = 'GTM-XXXX'

export default function trackPageView(url) {
    try {
      if (window.gtag)
        window.gtag("config", GA_TRACKING_ID, {
        page_location: url,
      });
  } catch (error) {
    console.log("Error from the trackerPageView => ", error);
  }
}

Solution I found temporary!

So currently my implementation of gtag let me to have firer and trigger detected by GTM, I just set a new trigger to

History modification

and now it's firing my events assigned with this trigger at each history modification. I'm not very confortable with gtag but this enough for me (for now), I'm still annoyed because of the implementation I did. I would like to find the right implementation to clean mine.

The problem clearly come from the SSR because the window variable is become undefined (don't exist in nodeJs) to the error above appear. Still search solution to fix it...

https://github.com/vercel/next.js/discussions/14980

Thx everyone and have a good day :)

like image 202
La pach' Avatar asked Jul 08 '20 09:07

La pach'


People also ask

How do you fix GTAG is not defined?

The error is because you have not implemented gtag on your website. Please check the option 'Add Global Site Tracking Code gtag. js' while configuring the plugin then this error would go away(Screenshot for reference).

What is window GTAG?

The Google tag (gtag. js) is a JavaScript tagging framework and API that allows you to send event data to Google Analytics, Google Ads, and Google Marketing Platform. This page describes how to use gtag.

Do I need GTAG?

Google Ads and Google Marketing Platform tags are fully supported by Tag Manager, and there is no need to deploy additional gtag. js-based code on your site if Tag Manager is already in use. If you're already using gtag. js, you can always upgrade to Tag Manager at a later date.

What does TypeError X is not a function mean?

TypeError: "x" is not a function The JavaScript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function.

What does the JavaScript error “is not a function” mean?

The JavaScript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function. Message TypeError: Object doesn't support property or method {x} (Edge) TypeError: "x" is not a function

What is ReferenceError window is not defined?

What is ReferenceError : window is not defined? How to fix ReferenceError : window is not defined? How to use Global variable in Node.js? The ReferenceError : window is not defined error mainly occurs if you are using the window object in Node.js, React.js, Next.js.

What happens if the window is not defined in JavaScript?

If it is defined, then the window execution takes place. We must remember that ‘ undefined ‘ should always be in single quotes, or the comparison will fail. The window is not defined reference error may also occur in case of browser execution. It can happen due to misspelled keywords or a mispositioned script tag.


Video Answer


1 Answers

You'll want to check for the existence of the window before using window.

For example:

if (typeof window !== 'undefined') {
  window.gtag("config", GA_TRACKING_ID, {
    page_location: url,
  });
}

Also you do not need to wrap your Google Tag Manager script in <Fragment>

Lastly, it looks like gtag is not something globally available by default. You have to set it up yourself according to this document: https://developers.google.com/analytics/devguides/collection/gtagjs

like image 146
james Avatar answered Sep 26 '22 22:09

james