How to Set Up Google Analytics for Canvas (Archived)

jperkins
Instructure
Instructure
119
62634

🛑 Please Read the Following before using this guide

This document is for a legacy implementation of Google Analytics on a deprecated version of Google Analytics no longer offered by Google. Do not attempt to use it. Instructure no longer uses Google Analytics in Canvas, and therefore updated documentation on using Google Analytics 4 (or similar) will not be provided by Instructure.  

An alternative option for Canvas usage data supported by Instructure is our Impact by Instructure product. Please reach out to your Instructure CSM or Sales representative if you'd like to explore this option.

If you still want to use Google Analytics, you should look into some of the below community resources if you are configuring Google Analytics for the first time. 

__________________________________________________________________________________

Using Google Analytics means that your institution is subject to Google's terms of service. Please verify with your institution's legal team before installing Google Analytics in your Canvas instance to ensure that you are in compliance with relevant laws and regulations.

New Custom Dimensions & Updated Script - May 31, 2019

A core code change to Canvas on Aug 28, 2019 may have broken your implementation of Google Analytics. Please install the updated code to restore functionality.

 

The steps below will help you get set up to use Google Analytics for Canvas. If you'd like to know more about why you might want to do this, please watch this Canvas Live session.

 

Create a Google Analytics Account

  1. Sign into Google
  2. Navigate to https://analytics.google.com  and click Sign Up
  3. Fill out the Form as desired, using your Canvas url in the website url field (eg: https://example.instructure.com) (or vanity url if you have one)
  4. Click "Get Tracking ID" button
  5. Accept Terms of Service
  6. Copy down the "Tracking ID" (eg: UA-12345678-1)

 

Set Up Tracking By User-ID New

Allows for more accurate session unification based on the user's Canvas ID, granting better user overtime metrics

  1. Navigate to the Admin Portal (If you just created your account you are already there)

  2. Click on "Tracking Info" to expand the menu item

  3. Click on "User-ID" option

  4. Read the agreements and follow the prompts

 

Add Custom Dimensions to Google Analytics Updated

This will let you pass custom variables from Canvas to Google Analytics such as User ID's, User Names, Course ID's and more.

  1. Navigate to the Admin Portal (If you just created your account you are already there)
  2. Click on "Custom Definitions" menu item
  3. Click on "Custom Dimensions menu item
  4. Click "+ NEW CUSTOM DIMENSION" button
  5. Add the following dimensions in order (If your index number is incorrect shared dashboards may not work)314355_pastedImage_7.png

 

Add Custom Javascript to Your Institution's Theme Editor

** Custom Javascript has been known to break things in Canvas. As of writing this post, May 31, 2019, it is working, but be aware that could change in the future.

  1. Download the attached Javascript File (If you cannot download for browser security reasons, you may copy and paste the code into a .js file from github. Minified Script. Non-minified Script.)
  2. Edit the File in a text editor
    • You'll need to customize line 3 (if using the minified version), or line 168 (non-minimized) with your tracking id number. Updated
    • //Working as of Aug 28, 2019
      function removeStorage(e){try{localStorage.removeItem(e),localStorage.removeItem(e+"_expiresIn")}catch(t){return console.log("removeStorage: Error removing key ["+e+"] from localStorage: "+JSON.stringify(t)),!1}return!0}function getStorage(e){var t=Date.now(),o=localStorage.getItem(e+"_expiresIn");if(null==o&&(o=0),o<t)return removeStorage(e),null;try{return localStorage.getItem(e)}catch(t){return console.log("getStorage: Error reading key ["+e+"] from localStorage: "+JSON.stringify(t)),null}}function setStorage(e,t,o){o=null==o?86400:Math.abs(o);var s=Date.now()+1e3*o;try{localStorage.setItem(e,t),localStorage.setItem(e+"_expiresIn",s)}catch(t){return console.log("setStorage: Error setting key ["+e+"] in localStorage: "+JSON.stringify(t)),!1}return!0}async function coursesRequest(e){let t=await fetch("/api/v1/users/self/courses?per_page=100"),o=await t.text();o=o.substr(9),o=JSON.parse(o);var s=JSON.stringify(o);return setStorage("ga_enrollments",s,null),parseCourses(e,s)}function parseCourses(e,t){if(null!=t){let s=JSON.parse(t);for(var o=0;o<s.length;o++)if(s[o].id==e)return s[o]}return null}function gaCourseDimensions(e){custom_ga("set","dimension4",e.id),custom_ga("set","dimension5",e.name),custom_ga("set","dimension6",e.account_id),custom_ga("set","dimension7",e.enrollment_term_id),custom_ga("set","dimension8",e.enrollments[0].type),custom_ga("send","pageview")}function googleAnalyticsCode(e){var t,o,s,n;if(custom_ga("create",e,"auto"),t=ENV.current_user_id,o=ENV.current_user_roles,custom_ga("set","userId",t),custom_ga("set","dimension1",t),custom_ga("set","dimension3",o),n=window.location.pathname.match(/\/courses\/(\d+)/)){n=n[1],s=0;try{let e=getStorage("ga_enrollments");if(null!=e){var r=parseCourses(n,e);null===r?coursesRequest(n).then(e=>{null===e?(custom_ga("set","dimension4",n),custom_ga("send","pageview")):gaCourseDimensions(e)}):gaCourseDimensions(r)}else coursesRequest(n).then(e=>{null===e?(custom_ga("set","dimension4",n),custom_ga("send","pageview")):gaCourseDimensions(e)})}catch(e){if((s+=1)>5)return custom_ga("set","dimension4",n),void custom_ga("send","pageview")}}else custom_ga("send","pageview")}!function(e,t,o,s,n,r,a){e.GoogleAnalyticsObject=n,e[n]=e[n]||function(){(e[n].q=e[n].q||[]).push(arguments)},e[n].l=1*new Date,r=t.createElement(o),a=t.getElementsByTagName(o)[0],r.async=1,r.src="https://www.google-analytics.com/analytics.js",a.parentNode.insertBefore(r,a)}(window,document,"script",0,"custom_ga");
      googleAnalyticsCode("UA-12345678-1"); // customize google analytics tracking number here‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
  3. Save the javascript file after making changes
  4. Upload the javascript file into your institution's Theme Editor
  5. Navigate back to Google Analytics and view real-time data to see if it is tracking real-time users on your account. Know that you may have to wait for 15 minutes or so to be able to see custom dimension data.

 

Build Dashboards & Reports in Google Analytics

  1. You may wish to get started by downloading the following dashboards:
  2. Build your own and once you get it the way you want, share the template URL in the comments on this document!

 

Embedded Custom Javascript File

There were issues with people copying the embedded Javascript. Please view the scripts on Github.

 

Changes Made (May 31, 2019) New

The updated script has undergone significant change. Below are some highlights of what the updated script does. The updated script is mostly backwards compatible with the previous version.

 

General Changes

  • Updated to remove any jQuery dependencies. Modern javascript is being used (may not work on Internet explorer). This means that API calls are now asynchronous and non-blocking. Improves performance.
  • Fixed a bug that meant some pageviews were never sent.
  • Added a timeout if API requests fail to avoid server spamming
  • Added support for Google Analytics User-ID tracking
  • Altered API Endpoint & Data Caching
    • Instead of pulling the course information (/api/v1/course/:course_id), the script pulls a user's courses ("/api/v1/users/self/courses?per_page=100") which includes an enrollment object and caches the returned value into local storage. The associated enrollment object allows us to set the "Canvas Course Role" dimension. Caching the data should also result in significantly better performance due to reduced API calls. If a course does not appear in the user's course list just the course_id and user dimensions will be sent (should only be for Admins and public courses).  Also it will only pull the first 100 enrollments for a user (let me know if you need support for pagination with the revised endpoint).

Dimension Changes

  • Canvas User RoleUpdated
    • Instead of filtering for a best match of a user's roles and only returning 1 value this is now a comma separated array of all of a user's roles. When filtering on this value, look use something like "contains" & "student" to get any users with a role of student. The data is still pulled from environmental variables. You should be able to build better Audience Segments from this data. (ie: Students should only have user, student, and maybe ta roles).
  • Canvas Term ID New
    • This can be a valuable filtering tool as much of Canvas built in reports filter on terms
  • Canvas Course Role New
    • By altering the way the script queries the course data, we are able to now capture the exact role the user has in a course. If a user has multiple user roles in a course, the value assigned to the pageview will always be the first role in the array. This should be a very useful dimension for building reports and analyzing course usage. If you think capturing all user roles will be helpful, let me know in the comments.
119 Comments