1

I'd like to prevent Google Analytics from logging events when developing my Angular 11 app on localhost. How do I do this?

So far, I've tried this:

if(window.location.hostname == 'localhost') {
  window['ga-disable-GOOGLE_TAG_HERE'] = true;
} else {
  window['ga-disable-GOOGLE_TAG_HERE'] = false;
}

which gives me the error:

Element implicitly has an 'any' type because index expression is not of type 'number'

Thanks in advance!

Milan Ferus-Comelo
  • 690
  • 1
  • 8
  • 20
  • 1
    Does this answer your question? [Can you test google analytics on a localhost address?](https://stackoverflow.com/questions/4375447/can-you-test-google-analytics-on-a-localhost-address) – hspaans Dec 25 '20 at 23:43

2 Answers2

0

One way to fix that specific error message is to modify your code like so:

if(window.location.hostname == 'localhost') {
  window[<any>'ga-disable-GOOGLE_TAG_HERE'] = true;
} else {
  window[<any>'ga-disable-GOOGLE_TAG_HERE'] = false;
}

or like this:

if(window.location.hostname == 'localhost') {
  window as { [key: string]: any })['ga-disable-GOOGLE_TAG_HERE'] = true;
} else {
  window as { [key: string]: any })['ga-disable-GOOGLE_TAG_HERE'] = false;
}
ulmas
  • 2,203
  • 16
  • 22
0

I would give you the advice to also include GA logging in development. If there are issues with the GA environment in development you can spot them directly.

The trick is to create separate views for development, test, acceptance, and live.

Raoul Dundas
  • 406
  • 4
  • 11