Universal Analytics event tracking - javascript

I have JS code that runs on my clients' websites and occasionally reports certain events to GA so that the clients can track them (they are almost click events). For clients that use universal analytics the code I use is:
if (typeof ga != "undefined") ga('send', 'event', category, action,opt_label);
and usually it works correctly (I'm using the GA debugger extension for chrome to see which values are sent) however with a couple of clients the GA debugger extension returns an error:
Command ignored. Unknown target: undefined
What does the error mean and why does it happen only on some sites?

In the error message:
Unknown target: undefined
The word "target" refers to the tracker object. If you're using GTM, it creates its own named tracker object in order to not conflict with any existing trackers on the page. But if there's no default tracker already on the page, then any ga('send', ...) or ga('set', ...) command will fail because they target the default tracker (which in this case doesn't exist).
This is normally not a problem because most analytics.js users use the default tracker, and most GTM user do 100% of their implementation configuration in GTM, and don't write analytics.js code at all, but if you do need to write your own analytics.js code and use GTM, you'll need to get the GTM tracker object, since the default tracker syntax won't work.
You can get a list of all created trackers in the following way, then you can send the event using the synchronous calling syntax:
ga(function() {
var allTrackers = ga.getAll();
var firstTracker = allTrackers[0];
firstTracker.send('event', category, action, opt_label);
});
Obviously if you have more than one tracker, you'll have to figure out which one is the GTM tracker.
For more information on working with named tracker objects and/or using multiple trackers, check out this developer guide:
https://developers.google.com/analytics/devguides/collection/analyticsjs/creating-trackers#working_with_multiple_trackers

Related

How to create Custom Dimension & get Unique PageView with GA4?

We're not sure if this is the right place for us to obtain the answers of such. We've contacted the Firebase Support Team but did not get the answers that we want except a few links to the online documentation that we've mostly been through before. After further clarifying our requests, we've not been receiving any response from them for 5 days; therefore we might as well try our luck here.
1. How to create a Custom Dimension in GA4?
As we understand, GA4 are all events now, including the Hit in Universal Analytics (UA), but how can we map from our UA custom dimensions to the GA4 model as shown below?
When we tried to create the AccCode custom dimension in GA4, we have no idea what to enter under the Event parameter dropdown list as it also cannot be dropped down whatsoever:
May I know how can we proceed from here and what should we enter for the Event parameter value?
2. How to get Unique PageView (UPV) in Firebase GA4 API?
In UA or GA v3, this is how we get our Page View and Unique PageView:
return jwt.authorize()
.then((response) => {
return google.analytics('v3').data.ga.get({
'auth': jwt,
'ids': 'ga:' + gaConfig.ViewerID,
'start-date': validatedDateRange.strStartDate,
'end-date': validatedDateRange.strEndDate,
'metrics': 'ga:pageviews,ga:uniquepageviews',
"dimensions": gaConfig.AccCodeDimension,
'filters': ${gaConfig.PageUrlDimension}!#googleusercontent.com;${gaConfig.PageUrlDimension}!#blogspot.com${!accCode ? "" : ";" + gaConfig.AccCodeDimension + "==" + accCode}`,
'sort': `${gaConfig.AccCodeDimension},-ga:pageviews,-ga:uniquepageviews`
}).then((gaQuery) => {
// Do something here
});
Below is the sample code that we found from the Firebase GA4 documentation:
import firebase from "firebase/app";
import "firebase/analytics";
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize Analytics and get a reference to the service
const analytics = firebase.analytics();
analytics.logEvent('select_content', {
content_type: 'image',
content_id: 'P12453',
items: [{ name: 'Kittens' }]
});
But the above sample code seems to be far from giving us an idea on how to achieve the same result as did in GA v3. It's more like logging of event data, potentially for our custom dimensions as what we did in the UA's tracking code. Examples for data pulling don't seem to be available in the documentation here. We need an equivalent example on how we can achieve the same result with Firebase GA4 API so that we can quickly migrate over to GA4 before July 2023.
We hope that someone here can help us to resolve the above two issues as quickly as possible because they involve changing the core engine of our app, which requires vast amount of development time and testing while the clock is ticking. Thank you so much in advance!
After so much of the studies and R&D, we realized that for what we're trying to achieve has nothing to do Firebase at all -- we can purely focus on GA and its latest API, which is still on Beta while some are on Alpha. But for the custom dimension creation, below is the answer:
Creating Custom Dimensions in GA4
As per the question described, the custom dimension creation process can be very confusing, especially to the UA users due to the change of data model and concepts. But what you need to know is that, you need to finalize your event parameters before mapping them over to the custom dimensions on GA console because the event parameter cannot be edited once the custom dimension is created on GA console:
So what you need to do is to extend your existing UA tracking code as shown below before creating your custom dimensions on GA console:
gtag('event','page_view', { // the page_view event is for web
"acc_code": "{{{AccCode}}}", // acc_code is your event parameter
"acc_name": "{{{AccName}}}", // This is another event parameter
"viewer_id": "{{{ViewerID}}}",
"viewer_title": "{{{ViewerTitle}}}",
"viewer_url": "{{{gaUrl}}}"
});
gtag('config', 'G-XXXXXXXX'); // This is your GA4 MEASUREMENT_ID
Data Query in GA4
For data query in GA4 that is equivalent to the given example in the question, please refer to the GA4 Data API here.
What about the Unique Pageview metric?
According to the GA documentation here, looks like Unique Pageview is no longer available in GA4:
I'm not sure if this is still subject to change, but you may need to write your own code, perhaps using sessionStorage or session cookies to track your own unique pageviews per user session for every page viewed.

How can I get Google Funding Choices to work with PreBid.js

We're using both GFC as our consent platform and client side PreBid along with Google DFP.
The implementation looks correct and most of the time we see the bids appearing correctly along with the consent tokens, however, on some occasions we get the following error message from prebid:
ERROR: CMP not found. Canceling auction as per consentManagement config. undefined.
We load both scripts asynchronously, but we do load Google's script first and then Prebid.js right after that.
We suspect that Google's implementation doesn't create the __tcfapi or __cmp objects immediately on the global scope, and that if those are not present, PreBid cancels the auction and doesn't fire the bids.
Did anyone else stumble upon this issue and can verify? Is there a way to prevent this from happening without delaying the page load or the ads? If not, is there a way to register an error handler on prebid?
We had the same problem. We use fundingchoices which is now integrated into Google AdManager.
Try
window.googlefc = window.googlefc || {};
window.googlefc.ccpa = window.googlefc.ccpa || {}
window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];
// wait for consent
googlefc.callbackQueue.push({
'CONSENT_DATA_READY': () => {
// do prebidding
}
});
But it seems to be very slow as the Google Publisher Tag (gpt.js) must be loaded which then decides that a FundingChoice/CMP is needed which gets loaded and then after a while the consent is available.
We don't have it production because it is too slow. Does somebody knwo how to speed things up with fundingchoice aka AdManger-GDPR-Messages

Implementation of Google Analytics pageView event on a single page application behave weird

I provide SEO services to a customer of mine.
The customer website uses AngularJS as a single-page-application using ui-router to swipe between pages (views).
I having troubles with sending pageView event for each different page, I've asked him to follow the instructions in this link.
He tried both:
ga('set', {
page: '/new-page',
title: 'New Page'
});
and:
ga('set', 'page', '/new-page');
for each route (page) on the site.
When I check Google Analytics 'real time' dashboard I can see the pageView(s)
but it count as the home page in the reports data.
I've tried implement it as GTM as well and still nothing.
p.s the routes look a bit different then regular ui-router routes, it looks like that:
http://www.example.com/s#!/page_name
Any idea why and what should I do to fix it?
appreciate any help, thanks :)
First - reconfigure tracker
This code seems to be OK, if you use default tracker and namespace names. After sending first pageview, you reconfigure tracker values. Your solution is right, because it keeps values for e.g. events fired later on virtual page.
ga('set', {
page: '/new-page',
title: 'New Page'
});
Second - send pageview again
After reconfiguring tracker, you have to send pageview again.
You do not show a lot of your code, but I am missing sending pageview. I expect you need to use some Angular router's method.
ga('send', 'pageview');
GTM alternations
The same is for GTM. Here you need firing event on virtual pageview and some data passed into dataLayer to update trackers values by page and title parameters. You have to recofigure Custom fields in PageView Tag settings.
Better debugging
If you have this kind of probles, please, add HTTP log (or console log from analytics_debug.js or whatever where is full signal).
Live HTTP headers, Omnibug, Charles Web debugging proxy or any other similar analyzer will help you.

Is it possible to message the dev-tools panel from within inspectedWindow.eval?

I have been reading over the chrome extension message passing documentation, but I cannot seem to establish communication from within the inspected window.
For example,
chrome.devtools.inspectedWindow.eval('function() {
.
.
.
/* send message to dev-tools panel */
chrome.runtime.sendMessage({foo:"foo"});<-- Uncaught Error: Invalid arguments to connect. Why is the extensionId required within chrome.devtools.inspectedWindow.eval? This made me step back and ask the question.
}')
I have tried leveraging both background and content scripts to listen for these messages, but nothing seems to trigger. My actual implementation is listening for WebSocket traffic, I left that out for brevity. I am able to listen to each request/response, however I cannot seem to establish communication within inspectedWindow.eval. In the end, my goal is to simply communicate with my dev-tools panel so I can update the UI.
Update
I found an interesting repo from someone that faced a similar issue. They however did not seem to find a valid solution. Could it be that this sort of messaging is not allowed by design?
https://github.com/thomasboyt/injectedWindow.eval-communication-sadness
You said you considered using a content script.
In that case, you can raise a custom DOM event, and the content script will be able to process it.
// Content script
window.addEventListener("RebroadcastExtensionMessage", function(evt) {
chrome.runtime.sendMessage(evt.detail);
}, false);
// Eval'd code
var message = {/* whatever */};
var event = new CustomEvent("RebroadcastExtensionMessage", {detail: message});
window.dispatchEvent(event);
The downside, of course, is that the page can listen in on those events if it so chooses as well as spoof them. If that's a serious concern, you can include nonces into event names and messages originating from dev tools. But then again, a really hostile page can override CustomEvent.. In a way, this is not a solvable problem, since anything you inspectedWindow.eval() fully shares context (and API access) with the page.

How to reliably get session id generated by Google Analytics?

Using the latest analytics.js code (as of today) is there a way through their JS API I can get the session id?
If you're talking about the client ID, you can get that as follows:
ga(function(tracker) {
var clientId = tracker.get('clientId');
console.log(clientId);
});
Here's where that's stated in the documentation:
https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#getting_the_client_id_from_the_cookie
Keep in mind that the client ID is (usually) stored in a cookie, so if the user clears their cookies, they'll be assigned a new client ID that may not match the one you have.
You can read the cookie created by Google but:
It's a privately (by google) chosen variable name/format and could change at any time, thus breaking your code
It appears to break their TOS if you store that information
https://webmasters.stackexchange.com/questions/51866/can-you-track-one-users-session-with-google-analytics-by-using-the-utma-cooki
Linking Google Analytics event logs to unique session ID
http://www.analytics-ninja.com/blog/2011/08/how-google-analytics-calculates-visits.html
Be aware! Some ad-blockers like uBlock Origin replaces GA script with its own polyfill.
This means that you can't correctly check is it real GA script are loaded on your page.
Also uBlock's polyfill changes GA API, so when you using ga(function(tracker){}) callback will never called!
So don't relay on callback and never wait for its calling
The better way is to manually store custom clientId in cookie and tell this clientId to GA
https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference?hl=en#clientId

Categories