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

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.

Related

Google Calendar API get Event details

I tried to get the event from Google Calendar of the specific date
function testing(){
var cal = CalendarApp.getCalendarById('moses#gmail.com');
var events = cal.getEvents(new Date("7/11/2022 07:30 AM"),new Date("7/12/2022 10:00 AM"));
for (var i=0;i<events.length;i++){
var title = events[i].getTitle();
var start_time = events[i].getStartTime();
var end_time = events[i].getEndTime();
}}
But I don't know how to get the same detail from Calendar when I schedule any meeting without specifying any date range.
My request is, I need to get the Title, Organizer Name, Start and End Time of the meeting when I schedule any meeting in Google Calendar.
Moment I press Save in the Calendar, My script needs to trigger and get the details of the meeting I scheduled in calendar.
This can get complicated and you won't be able to only use Google Apps Script for it.
I believe your question boils down to two requirements:
Knowing when a new event has been created.
Getting the details of this newly created event to use as you see fit.
For #1, you can know when a calendar gets modified by using push notifications. The way this works is that you send a POST request to the Calendar's watch endpoint, with headers specifying the URL of a server that you want to set up as a webhook. This server will receive POST notifications when the Calendar gets updated and you can then handle them. A few caveats:
There are no native Apps Script functions that can use this, so you need to create your own GCP project, and generate the Authorization token to include in your request to create the webhook.
You will need to set up your own server to handle the callbacks. You cannot use Apps Script as a Web App because the callbacks contain all their information in their HTTP headers, and the doPost() method does not contain the headers, as explained in this question. Since the notifications work by sending POST messages, Apps Script won't work here.
The notifications are not 100% reliable. A small percentage of messages may get dropped so you won't always know that there was a change.
As for #2, the problem here is that the push notifications are only meant to notify your app that a change was made so it can handle the syncing on its own. This means that they don't include any details about what exactly changed, so you cannot know which event was created or changed, you only know that the calendar was somehow changed, and it's up to you to figure out what it was.
Google recommends using incremental sync, which means that you first sync all events, then use the syncToken they provide to get only changed events. You can use this to figure out which events changed since you got the notification, but you may have to refresh a full sync sometimes, so rather than just picking up new events, your app is now in charge of fully syncing the Calendar.
If this is all too much work you can still try to list events using the updatedMin parameter to only list events more recently modified than a specific date/time. You can use this with Apps Script's Advanced Calendar Service. You could do this periodically, but you won't have the instant trigger you're looking for.
Sources
Node.js sample of how to use webhooks
Push Notifications
Advanced Calendar Service
Synchronizing calendars

Retrieve single Calendar Event using API v3 in javascript

I have modified the script found here Retrieve Google Calendar events using API v3 in javascript to display a page of upcoming events over the next 30 days which summarizes each event.
I would like to create a link provided with each event summary on the above page to another page that would show more details for a specific single event.
I cannot seem to write the code that will successfully take the eventId and query the Google Calendar API to retrieve the resources for that single event.
I apologize in advance as I am trying to learn Javascript as I go so I suspect this is something rather simple that I'm stuck on.
I am of the belief that in the makeApiCall() function I would desire to change the lines that start with:
var request = gapi.client.calendar.events.list({
to:
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.get({
'calendarId' : userEmail,
'eventId': eventIDstr});
I can get a valid answer when using Google's APIs Explorer pages so I know I have the correct Calendar and Event IDs. Just cannot seem to apply that to the correct javascript to get the results I am looking for.
I have searched high and low for samples of javascript that will retrieve a single Event's data from Google Calendar using v3 of their API and have come up with nothing useful. Any help would be greatly appreciated.
Thanks in advance.
Yes, you're on the right path. Use Events:get. Events provides different flavors of event resources.
HTTP request
GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events/eventId
If successful, method returns an event resource in the response body.
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.model.Event;
// ...
// Initialize Calendar service with valid OAuth credentials
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credentials)
.setApplicationName("applicationName").build();
// Retrieve an event
Event event = service.events().get('primary', "eventId").execute();
System.out.println(event.getSummary());
You can use singleEvents=true parameter in the list request to avoid the second call. This will ask the server to do the recurring event expansion for you right away.

AngularJS Google Analytics Dynamic tracker

I am attempting to set up two analytics trackers in my Angular App. One of my requirements is to set up a tracker for every user that logs in to the app that forwards page tracking and event data to a static tracker known at config time. However, the second tracker needs to be set during runtime once a user is logged in. It needs to send analytics data to a tracker that is associated with their account.
I am new to using google analytics and thought it would be as easy as pushing to the ga command queue to trackers but after reading the analytics developer literature it seems that I would have to explicitly send page track commands to both trackers.
So instead of re-inventing the wheel I looked at revolunet/angular-google-analytics hoping that it would solve my problem. However, it complains about not setting the tracker at run-time. I tried using
AnalyticsProvider.delayScriptTag(true);
then mutating the array
Analytics.configuration.accounts;
at runtime but it seems to produce no effect.
If anyone has had experience with this in the past please let me know, i'm looking for a clean Angular-ish solution besides putting a wrapper around the ga command queue unless that's my best bet.
Thanks!
A little late in the response but to those it may help I ended up creating an analyticsService that is responsible for setting up the dynamic tracker. In order for it to work I added the following to my app's config
AnalyticsProvider.delayScriptTag(true);
AnalyticsProvider.ignoreFirstPageLoad(true);
AnalyticsProvider.setPageEvent('$stateChangeSuccess');
This delayed the initialization of the auto tracking. Then I forked angular-google-analytics and added the following code
this._kickOffAutoTracking = function() {
// activates page tracking
if (trackRoutes) {
$rootScope.$on(pageEvent, function () {
that._trackPage();
});
}
};
Finally in my analyticsService I made my API request, got the user's tracker and added it as follows:
Analytics.setAccount([
{ tracker: DEFAULT_TRACKER, name: "defaultTracker", trackEvent: true },
{ tracker: user.analyticCode, name: "userTracker" }
])
Analytics.createAnalyticsScriptTag();
Analytics.kickOffAutoTracking();
It was a quick an dirty solution.

Set Google Analytics User ID after creating the tracker

The Google Analytics User ID documentation page shows that you set the User ID when you create the tracker. I have a javascript only project with sign-in after page load, is there any way to set the User ID after login? Something like ga("set", "userid", "UNIQUEID")
On the field reference page it says you can only set user-id in the create function. Are we able to call create again with the user-id? Will that create a new tracker, or override the old one?
EDIT: The beta version of User ID tracking showed that you could specify the userid after creating the tracker using ga('set', '&uid', {{ USER_ID }}); and that would try to unify the session from before the userid was set with the one after. That seems to be very different than what the docs current specify. Is there any way to do this with the current method?
This one works
ga('set', '&uid', '<dynamic user id here>');
The documentation seems to indicate that, with analytics.js, you should do the following:
// Alternatively, you may set the user ID via the `set` method.
ga('set', 'userId', 'as8eknlll');
I'm not sure how this differs from the current answer (which uses &uid), but this solution is working for us.
You should set userId beofre sending event to Google Analytics. I couldn't manage to send userId after sending events pageview and ecommerce:send.
It appears from Justin Cutroni's blog that he's saying that data stitching (in your case matching the userid prior to login to the userid post-login) is not currently offered in Google Analytics.
http://cutroni.com/blog/2014/04/10/understanding-cross-device-measurement-and-the-user-id/
See specifically this sentence: "Google Analytics will not go back in time and stitch every single session from a given user together."
If you are using Google Tag Manager you can set the User ID by added '&uid' as a field to your Google Analytics Setting variable:

Using and querying Custom Dimensions in Google Analytics API

I am attempting to query my Analytics (Universal) to receive a list of metrics sorted by a custom dimension.
In July, the Google Analytics API blog announced:
"Developers can use custom dimensions to send unique IDs into Google Analytics, and then use the core reporting API to retrieve these IDs along with other Google Analytics data.
For example, your content management system can pass a content ID as a custom dimension using the Google Analytics tracking code. Developers can then use the API to get a list of the most popular content by ID and display the list of most popular content on their website."
Despite this, I have been unable to retrieve any results from my Analytics. My send function is below:
ga('send', 'pageview', {
'dimension1':'red'
});
Unfortunately, querying GA using a filter of 'ga:dimension1 == red' does not retrieve any results.
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + "123456",
'start-date': '2013-11-10',
'end-date': '2013-11-20',
'metrics': 'ga:visits',
'filters': 'ga:dimension1==red'
}).execute(function(r){console.log(r);});
I have also tried using custom segments to retrieve the data, to no avail:
'segment': 'dynamic::ga:dimension1==red'
The data appears in Custom Reports in GA. How can I access it via the API?
You need to include a the dimension in the query. Such as 'dimension': 'ga:dimension1', then use your filter 'ga:dimension1==red'. The Query Explorer is very helpful for testing API requests.
hey this is very helpful. thanks so much for the answer.
Let me also answer this question with an example:
let so for a ga defined dimension, the syntax would look like - ga:landingPagePath=="what ever you want"
now say there is a custom dimension called pagepath which is customdimension1 .
Hence the syntax will be ga:dimension1=="what ever you want"

Categories