How to check if GA4 or Universal Analytics is installed? - javascript

I'm trying to detect on websites using Javascript if they have the new GA4 installed or the old Universal Analytics.
While for UA detection I can use typeof(ga) !== "undefined", not sure how to do this for GA4.
Based on information here: Seems to be using also ga? Any other difference that we can use on client side?

hy,
we use to do it like this for GA4:
if(typeof gtag === 'function' ){
gtag('event', 'myeventname',{
'event_category': 'myeventcategory'
});
}
please note that this will only work if you have GA4 tracking code installed directly in your page. if you use google tag manager, this won't work.

For detecting Google Analytics 4 (GA4) on a website, you can check for the existence of the gtag function, as GA4 uses the gtag.js library. Here's an example:
if (typeof gtag === "function") {
console.log("Google Analytics 4 is installed on this website.");
} else {
console.log("Google Analytics 4 is not installed on this website.");
}
Note that if both GA4 and Universal Analytics (UA) are installed on the same website, you will need to use the gtag function to send data to GA4 and the ga function to send data to UA. In that case, you will also need to make sure to send the data to the correct property by specifying the correct tracking ID.

Related

How to only read Google maps API key in production

I'm working on a React application that uses Google maps. I've been working on it in development mode only and would like to add the API key now when I push it to production.
I'm loading the Google Maps script like the code below and it seems to work, but I would like to only read from my .env and use the API key in production, not when I develop locally on http://localhost:3000/, etc. Does anyone know if there is a simple way to do this?
if (!scriptElementExists) {
// Create a new script tag
const scriptElement = createScriptElement(
'google-maps',
`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAPS_KEY}&callback=${googleMapsData.scriptCallbackName}`
);
// Append the script to the document
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
My .env
# Google Maps Api Key
REACT_APP_GOOGLE_MAPS_KEY={{API_KEY}}
Thanks beforehand!
And please ask if I've made myself clear.
If you are using Create React App you can use process.env.NODE_ENV.
It is set automatically to development or production.
https://create-react-app.dev/docs/adding-custom-environment-variables

Google Analytics using React Web / Cordova

I have made an app using React (Web) and bundled it using Cordova.
I am using a plugin called 'react-ga' for tracking Google Analytics.
I initialise react-ga when the app is run using:
ReactGA.initialize('my-ga-uid', { debug: true, cookieDomain: 'auto' })
And create an event using something like:
ReactGA.event({
category: 'Test',
action: 'Test button pressed event.'
})
or,
ReactGA.set({ location.pathname })
ReactGA.pageview(location.pathname)
The analytics work fine in the browser and on dev builds, however when I bundle a build for iOS or Android, the analytics don't seem to be tracked?
Is there something wrong with my code? Do I need to initialise something else? Do I need a cordova plugin instead (although I want analytics to still work in a web browser)?
ReactGA.set({ checkProtocolTask: null }) // Disable file protocol checking.
You may need to create a GA property for your mobile app that is a separate property from your website. When you set up a new property, you have the option to choose between a website and a mobile app.
I was using ReactGA in an Android webview:
I needed to do the following:
ReactGA.set({ checkProtocolTask: null, checkStorageTask: null })
to get passed the following errors:
"Unallowed document protocol. Aborting hit"
"Storage not available. Aborting hit."

How to add Google Analytics Event via PHP?

GA Events in Javascript we can do by
ga('send', 'event', 'test', 'test','value');
I need to implement this in entire project. But there are some sections where I need to do it via PHP.
So looking for PHP library that can be added as a module via composer.
I found
Google Analytics Measurement Protocol library for PHP
PHP Analytics Events
But this one is not best. That which I'm looking for.
Tracking Id & Website only specified by once. Then just need to pass event parameters as we do in Javascript.
Does anyone come across any kind of this library?
Found this one very helpful
https://gearside.com/using-server-side-google-analytics-sending-pageviews-event-tracking/
The Google analytics javascript snippet sends data to google analytics via the measurment protocol
The measurement protocol accepts http post and http gets. This can easly be done with PHP but if you are looking for something out of the box created to do it there isnt anything official written in php that i am aware of. Your going to have to code this yourself.
Using
https://github.com/thomasbachem/php-ga
Install via
composer require united-prototype/php-ga
Below is the code
use UnitedPrototype\GoogleAnalytics;
$tracker = new GoogleAnalytics\Tracker('UA-XXXXXX-1', 'example.com');
$session = new GoogleAnalytics\Session();
// Setup visitor
$visitor = new GoogleAnalytics\Visitor();
$visitor->setIpAddress($server->get('REMOTE_ADDRESS'));
$visitor->setUserAgent($server->get('HTTP_USER_AGENT'));
//Set Event
$event = new GoogleAnalytics\Event();
$event->setCategory('Category'); // Event Category (Required)
$event->setAction('Event'); // Event Action (Required)
$event->setLabel('Label'); // Event Label (Optional)
$event->setValue(1); //integer, not required
//track event
$response = $tracker->trackEvent($event,$session,$visitor);
Works fine for me.

How to implement Google Analytics event tracking inside a React VR project?

This is loosely written to give a basic idea of what I'm trying achieve.
< VrButton onClick={props.userClick}>< /VrButton>
userClick={() => this.triggerTracking}
triggerTracking() {
ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
}
I expect the code to trigger Google Analytics event tracking in the GA system when the user clicks on a button, but I get an error message - "ga is not a function".
I have GA set up in my index.html file, with the proper ID, and pulling in the latest analytics.js API.
React VR is all within a web worker context so it is not possible to access anything on your window without the use of native modules.
You can embed them directly in your client js and use the GA tracking functions as you normally would there. You will then call a function on your native module within your react VR app.
You can check out the documentation here: https://facebook.github.io/react-vr/docs/native-modules.html
Try using the window scope as:
window.ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
I'm not familiar with React at all, but perhaps React causes some abstraction between the window and the react scope, making your ga() function unavailable.
Do next stps:
open the network debug tool of your browser.
reload your page
review loaded url list and check that www.google-analytics.com/analytics.js is loaded
If you does not see such url loaded - read google analitycks manual about how to setup google analytics on your page.
If you see such url replace url www.google-analytics.com/analytics.js with www.google-analytics.com/analytics_debug.js in your page, than reload and than go to console tab of your browser debugger and check the errors.

Determine if Google Analytics is loaded

I'm trying to track specific actions using Google Analytics, but I don't want to track them locally when I'm developing the site. Locally I don't load Google Analytics, so I'm trying to only enable the tracking if GA is loaded. When I added the condition shown below it stopped tracking actions, any thoughts on why?
if (typeof _qag != "undefined") {
_gaq.push(['_trackEvent', ucfirst(Site.page.tabs.main.getSelected().attr('data-siteName'))+' Tab', 'Clicked deal header', ucfirst(Site.page.tabs.getSelected().attr('data-siteName'))]);
}
Shouldn't it be "_gaq" instead of "_qag" on your if?
That way it's always false.

Categories

Resources