user11950120
user11950120

Reputation:

TypeError: Illegal Invocation

We're running a Create React App (CRA) web app, to which we've added Google Analytics v4. We initiate analytics using the ga-4-react npm package. Manual initialization in index.js

const ga4react = new GA4React(process.env.REACT_APP_GOOGLE_ANALYTICS_ID);

ga4react.initialize().then((ga4) => {
    ga4.pageview(window.location.path);
}, (err) => {
    Sentry.captureException(err);
});

We're receiving hundreds of errors from the gtag/js file to our Sentry error monitoring platform. This error doesn't really say much to us and we've spent two days trying to find out if anyone's run into a problem like this, but so far we've come up empty. It also doesn't seem to affect user experience, but it's rather annoying for us to monitor.

The error is reported as so to Sentry.

TypeError zq(gtag/js)
Illegal invocation

gtag/js in zq at line 477:453
{snip} ))}}},zq=function(a,b,c){var d=a+"?"+b;c?$c.sendBeacon&&$c.sendBeacon(d,c):pd(d)};var Eq=window,Fq=document,Gq=function(a){var b=Eq._gaUserP {snip}

We also receive as many errors from ga-4-react (the catch-block in the code snippet above). We also tried using the analytics snippet with react-helmet, but had the same result.

This error seems to be generated by a number of browsers (Chrome, Opera, Safari, mobile browsers) on many platforms (Android, Windows 10, OS X) so we can't really pinpoint any specific route, platform, browser that's common with these users.

I also tried to replicate this with AdBlock, blocking trackers, using Do Not Track, but nothing.

Upvotes: 15

Views: 15176

Answers (5)

Rana Nadeem
Rana Nadeem

Reputation: 1225

Working for me. processData: false, contentType: false, is required for working.

var formData = new FormData($('#author_post')[0]);
 formData.append('t','author-add');
 $.ajax({
        type: 'POST',
        url: 'url-here',
        cache: false,
        processData: false,
        contentType: false,
        data:formData,
        success: function(response) {
           //success code
        }
 });

Upvotes: -2

Richard Kreutz-Landry
Richard Kreutz-Landry

Reputation: 131

Ran into the same issue on our site. This issue appears to stem from navigator.sendBeacon being called out of context, similar to the comment from hackape.

For context, this article has some pretty good info on sendBeacon and what it does, including a description of an error like the one you saw.

https://xgwang.me/posts/you-may-not-know-beacon/

In our case, we only saw Type Error: Illegal Invocation, but didn't see the other error message variants based on different browsers that they mentioned. In the end we ignored it in sentry for the moment.

Upvotes: 9

Ionuț Păduraru
Ionuț Păduraru

Reputation: 339

You are using ga4.pageview(window.location.path); but path is not a property of window.location

Try using pathname instead:

ga4.pageview(window.location.pathname);

Upvotes: 0

Nikhil
Nikhil

Reputation: 99

Use react-ga npm package for implementing Google Analytics with below code

Create helper file, which will help you for DRY concept

import ReactGA from 'react-ga';

/**
 * Initialize Google Analytics
 */
export const initializeGA = () => {
  ReactGA.initialize(process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_KEY, {
    debug: true
  });
};

/**
 *  Push Page Tracking on Google Analytics
 */
export const pageView = () => {
  ReactGA.pageview(window.location.pathname + window.location.search);
};

Then initialize Google Analytics on your root component

import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { initializeGA, pageView } from '../helpers/analytics';

export default function MyApp() {
  const location = useLocation();

  useEffect(() => {
    initializeGA();
  }, []);

  useEffect(() => {
    pageView();
  }, [location.pathname]);

  return (
    <div>
      <p>Your root component text</p>
    </div>
  );
}

If you are using old React versions it can be implemented using class component and lifecycle hooks componentDidMount, componentDidUpdate/componentWillRecieveProps based on your react version. Sample for the same is.

import { browserHistory } from 'react-router';

class App extends React.Component {
  componentDidMount() {
    this.unlisten = browserHistory.listen((location) => {
      console.log('route changes');
    });
  }
  componentWillUnmount() {
    this.unlisten();
  }
  render() {
    return (
      <div>
      </div>
    );
  }
}

Upvotes: 0

Renu Yadav
Renu Yadav

Reputation: 149

You can use this code example

import React from "react";
import ReactDOM from "react-dom";
import GA4React, { useGA4React } from "ga-4-react";

const ga4react = new GA4React("G-1JXXXXX");

function MyApp() {
  const ga = useGA4React();
  console.log(ga);

  return <div className="App">hi!</div>;
}

(async () => {
  await ga4react.initialize();

  ReactDOM.render(
    <React.StrictMode>
      <MyApp />
    </React.StrictMode>,
    document.getElementById("root")
  );
})();

Upvotes: 1

Related Questions