How to Set Up Google Analytics for Canvas

Document created by Jeremy Perkins Employee on Apr 6, 2017Last modified by Jeremy Perkins Employee on Jun 3, 2019
Version 13Show Document
  • View in full screen mode

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.

This outlines the use of Google Analytics without Google Tag Manager. This is an old implementation. You may want to look into some of these other community resources if you are configuring Google Analytics for the first time. It does require a little bit more upfront time to get configured, but is considered the new way of doing Google Analytics.

New Custom Dimensions & Updated Script - May 31, 2019

 

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)

 

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 May 31, 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(),n=localStorage.getItem(e+"_expiresIn");if(null==n&&(n=0),n<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,n){n=null==n?86400:Math.abs(n);var r=Date.now()+1e3*n;try{localStorage.setItem(e,t),localStorage.setItem(e+"_expiresIn",r)}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"),n=await t.text();n=n.substr(9),n=JSON.parse(n);var r=JSON.stringify(n);return setStorage("ga_enrollments",r,null),parseCourses(e,r)}function parseCourses(e,t){if(null!=t){let r=JSON.parse(t);for(var n=0;n<r.length;n++)if(r[n].id==e)return r[n]}return null}function gaCourseDimensions(e){ga("set","dimension4",e.id),ga("set","dimension5",e.name),ga("set","dimension6",e.account_id),ga("set","dimension7",e.enrollment_term_id),ga("set","dimension8",e.enrollments[0].type),ga("send","pageview")}function googleAnalyticsCode(e){var t,n,r,o;if(ga("create",e,"auto"),t=ENV.current_user_id,n=ENV.current_user_roles,ga("set","userId",t),ga("set","dimension1",t),ga("set","dimension3",n),o=window.location.pathname.match(/\/courses\/(\d+)/)){o=o[1],r=0;try{let e=getStorage("ga_enrollments");if(null!=e){var a=parseCourses(o,e);null===a?coursesRequest(o).then(e=>{null===e?(ga("set","dimension4",o),ga("send","pageview")):gaCourseDimensions(e)}):gaCourseDimensions(a)}else coursesRequest(o).then(e=>{null===e?(ga("set","dimension4",o),ga("send","pageview")):gaCourseDimensions(e)})}catch(e){if((r+=1)>5)return ga("set","dimension4",o),void ga("send","pageview")}}else ga("send","pageview")}!function(e,t,n,r,o,a,s){e.GoogleAnalyticsObject=o,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,a=t.createElement(n),s=t.getElementsByTagName(n)[0],a.async=1,a.src="https://www.google-analytics.com/analytics.js",s.parentNode.insertBefore(a,s)}(window,document,"script",0,"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.

Outcomes