@telefonica/google-analytics
v1.0.3
Published
> Google Analytics 4 library for Telefonica web projects
Downloads
256
Readme
@telefonica/google-analytics
Google Analytics 4 library for Telefonica web projects
Usage
import {initAnalytics, setUserProperty, logEvent, setScreenName} from '@telefonica/google-analytics';
initAnalytics('G-XXXXXXXXXX');
setUserProperty('my_user_property', 'my_user_property_value');
setScreenName('my_screen_name');
logEvent({name: 'my_event_name', foo: 'bar'});
Things to know
initAnalytics
must be called before any other function. This function will inject the gtag script in the document.initAnalytics
function is idempotent. Subsequent calls toinitAnalytics
will not have any effect.logEvent
andsetScreenName
calls won't send any data to Google Analytics untilinitAnalytics
is called. If you calllogEvent
orsetScreenName
beforeinitAnalytics
, the calls will be queued and sent to Google Analytics onceinitAnalytics
is done.Events are normalized before being sent to Google Analytics:
- Event params name are truncated to 40 characters.
- Event params value are truncated to 100 characters.
- Not allowed characters are removed from event params value.
- Multiple white spaces are removed and spaces are replaced by underscores in event params value.
- The same normalization is applied to screen names.
If
setScreenName
is called multiple times with the same screen name, only the first call will be sent to Google Analytics.setScreenName
andlogEvent
return a promise that resolves when the event has been sent to Google Analytics.All the events are automatically filled with a
screenName
param containing the last screen name set withsetScreenName
.
Use custom Api
Events are sent to Google servers by default (using gtagApi
), but you can use a custom api to change this
behavior. For example, Novum app uses the webview bridge to send the events to the native app, and then the
native app sends the events to Firebase.
Another use case of custom api is to log events in the browser console in development mode:
import {initAnalytics, consoleApi, gtagApi} from '@telefonica/google-analytics';
initAnalytics('G-XXXXXXXXXX', {
api: process.env.NODE_ENV === 'production' ? gtagApi : consoleApi,
});
CSP
If you are using a CSP, you must add the following directives for Google Analytics to work:
script-src https://*.googletagmanager.com; connect-src https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com; img-src https://*.google-analytics.com https://*.googletagmanager.com;
Check Google docs for CSP in Google Analytics 4