Google Analytics 4

Jump to solution
martin_kabat
Community Participant

Hi all,

Has anyone managed to setup Google Analytics 4?

 

2 Solutions
dtod
Community Contributor

This should work. I've got the rest of it working too, but this bit should take of loading it.

$.ajax({
	url: 'https://www.googletagmanager.com/gtag/js?id=YOURID',
	dataType: 'script',
	cache: true,
	})

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'YOURID');

 

View solution in original post

dtod
Community Contributor

This is the original code I started with: https://github.com/japerks/canvas_scripts/blob/master/updated_google_analytics_cache.js

Fundamentally, I replaced custom_ga with gtag

And removed all "send" lines.

I'm still testing and validating a bit.

For example:

function gaCourseDimensions(course) {
    custom_ga('set', 'dimension4', course['id']);
    custom_ga('set', 'dimension5', course['name']);
    custom_ga('set', 'dimension6', course['account_id']);
    custom_ga('set', 'dimension7', course['enrollment_term_id']);
    custom_ga('set', 'dimension8', course['enrollments'][0]['type']);
    custom_ga('send', 'pageview');
    return
}

I think I'd named the variables somehow. I forget when, so this became

function ga4CourseDimensions(course) {
    gtag('set', 'course', course['id']);
    gtag('set', 'course_code', course['course_code']);
    gtag('set', 'account_id', course['account_id']);
    gtag('set', 'role', course['enrollments'][0]['type']);
    return
}

 I removed some elements that are local to us, but the idea is there.

Still working on it a bit, but it seems to be working. I'll admit that I do not find GA4 as easy to wrap my head around as UA.

View solution in original post