cancel
Showing results for 
Search instead for 
Did you mean: 

Admin Group

Surveyor

Like many of you out there, here at Utah State University, we are struggling to move all of our classes online in an absurdly short period of time in response to COVID-19.

To help speed up the process, I have created some JavaScript to facilitate rapidly pulling a template course into an empty course shell and I am sharing it in the hopes that it can alleviate some of the headaches for other institutions.

I am providing the code for two contexts, uploading JavaScript to Canvas using the Canvas Theme Editor and creating a browser bookmarklet for those who do not have access to account-level JavaScript in Canvas.


A Note About Permissions

The code that follows will run as the logged-in user and will only work if the user has permission to import course content in Canvas.

The code is also scoped to only show on the front-page of an empty course so it should not be visible to students.

Account Level JavaScript

Canvas allows for adding CSS and JavaScript at an account level using the Canvas Theme Editor. For institutions that want to provide this type of functionality for an entire account, here are two options:


Single Template Course

If you have a single template course that you would like to provide an easy way to copy, the following code will create an Insert Base Template button in the right Canvas sidebar:

Insert Base Template Button

Here is the code that you would upload to Canvas. Update the templateCourse id on line 36 to your template course:

// Import Base Template button for the course Home Page
// This function will keep checking the progress url until process is complete or fails
function checkImportProgress(progressUrl) {
$.get(progressUrl, function(data) {
// Update the button to show we are checking again
$('.kl-import-template').html('Checking Progress');
// Four possible options
// 'queued', 'running', 'completed', 'failed'
let completed = false;
switch(data.workflow_state) {
case 'completed':
completed = true;
break;
case 'failed':
alert('Import failed');
break;
default:
// For 'queued' or 'running'
setTimeout(function(){ checkImportProgress(progressUrl); }, 5000);
}
if (completed) {
// Reload the course home page
location.reload();
} else {
// Wait a bit and try again
setTimeout(function(){ checkImportProgress(progressUrl); }, 5000);
}
// Provide feedback of the current progress
setTimeout(function(){
$('.kl-import-template').html('Template Progress: ' + data.workflow_state);
}, 1000);
});
}
$(document).ready(function() {
// The Canvas course id for your template
let templateCourse = '593';
// Only add the button to the home page of courses without any other content in place
if (ENV.COURSE !== undefined && ENV.COURSE.id !== null && window.location.pathname === '/courses/' + ENV.COURSE.id && $('.ic-EmptyStateList:visible').length > 0) {
// Add the import button
let importButton = '<button class="btn btn-primary button-sidebar-wide kl-import-template"><i class="icon-download"></i> Import Base Template</button>';
$('.kl-import-template').remove();
$('.course-options').prepend(importButton);
// Bind action
$('.kl-import-template').unbind('click').on('click', function () {
// Prompt user so they have a chance to cancel
let confirmMessage = confirm("This will copy content into your course. Click OK to proceed.");
if (confirmMessage == true) {
$(this).html('Importing Base Template');
// Send import request to the Canvas API
$.post('/api/v1/courses/' + ENV.COURSE.id + '/content_migrations', {'migration_type': 'course_copy_importer', 'settings[source_course_id]': templateCourse}, function(data, textStatus, xhr) {
// Begin checking the progress url to see when import is complete
checkImportProgress(data.progress_url);
});
}
});
}
});

Multiple Template Courses

This next variation is for institutions with multiple templates. Instead of a single button, this will add a list of courses with the option to preview and a brief description:

Template list

Here is the code that you would upload to Canvas. Update the templateList that begins on line 4 to include a name, id, and description for each of your template courses:

// Create a list of templates on the home page of a blank course 
$(document).ready(function() {
// This is the list of your templates (Duplicate as needed)
let templateList = [
{
name: 'Basic Online Template',
id: '593',
description: 'Basic 8 week course with readings, assignments, and quizzes'
},
{
name: 'Another Template',
id: '1234',
description: 'This is a good course template'
}
];
// Function to check the Canvas progress url to see if the course has finished importing
function checkImportProgress(progressUrl, courseID) {
$.get(progressUrl, function(data) {
// Give a visual cue that we are going to check again
$('#kl-import-progress').html('Checking Progress');
// 'queued', 'running', 'completed', 'failed'
let completed = false;
switch(data.workflow_state) {
case 'completed':
completed = true;
$('#kl-import-progress').attr('class', 'alert alert-success');
break;
case 'failed':
$('#kl-import-progress').attr('class', 'alert alert-error').html('Import failed');
break;
default:
// for 'queued' or 'running'
setTimeout(function(){ checkImportProgress(progressUrl, courseID); }, 5000);
}
if (completed) {
// Change from institution visibility to course
// If you set the template visibility to 'institution', users can preview before they copy
let parms = {
'course[is_public_to_auth_users]' : false,
'course[is_public]' : false
};
$.ajax({
'url' : '/api/v1/courses/' + courseID,
'type' : 'PUT',
'data' : parms
});
// Import is complete, reload the page
location.reload();
} else {
// Import isn't finished, wait a bit and try again
setTimeout(function(){ checkImportProgress(progressUrl, courseID); }, 5000);
}
setTimeout(function(){
$('#kl-import-progress').html('Template Progress: ' + data.workflow_state);
}, 1000);
});
}
// Only add the button to the home page of courses without any other content in place (shows import option)
if (ENV.COURSE !== undefined && ENV.COURSE.id !== null && window.location.pathname === '/courses/' + ENV.COURSE.id && $('.ic-EmptyStateList:visible').length > 0) {
// Add a placeholder to the sidebar
$('#kl-template-list').remove();
$('.course-options').prepend('<div id="kl-template-list"></div><div id="kl-import-progress"></div>');
// Add each template to the list
$.each(templateList, function(index, val) {
let itemInfo = `<p>
<a href="/courses/${val.id}" target="_blank" data-tooltip="left" title="${val.description}" class="Button Button--secondary kl-preview-template" style="padding: 2px 6px;"><i class="icon-eye"></i><span class="screenreader-only">View ${val.name}</span></a>
<button class="Button Button--secondary kl-import-template" data-tooltip="top" title="Import ${val.name}" data-courseid="${val.id}" style="padding: 2px 6px;"><i class="icon-download"></i><span class="screenreader-only">Import ${val.name}</span></button>
<span class="kl-template-name-${val.id}">${val.name}</span>
</p>`;
$('#kl-template-list').append(itemInfo);
});
// When template import is clicked
$('.kl-import-template').unbind('click').on('click', function () {
// Give user a chance to cancel
let confirmMessage = confirm("This will copy content into your course. Click OK to proceed.");
if (confirmMessage == true) {
let templateCourse = $(this).attr('data-courseid');
let templateName = $(`.kl-template-name-${templateCourse}`).text();
$('#kl-import-progress').addClass('alert alert-info').html(`Importing ${templateName}`);
// Send import request to the Canvas API
$.post('/api/v1/courses/' + ENV.COURSE.id + '/content_migrations', {'migration_type': 'course_copy_importer', 'settings[source_course_id]': templateCourse}, function(data, textStatus, xhr) {
// Begin checking the progress url to see when import is complete
checkImportProgress(data.progress_url, ENV.COURSE.id);
});
}
});
}
});

JavaScript Bookmarklets (No access to add JavaScript to Canvas)

Next, let's take a look at some options for those who do not have access to add JavaScript to Canvas using the Theme Editor at an account level.


What is a Bookmarklet?

A bookmarklet is similar to create a bookmark in your browser to take you to a webpage. The difference is that instead of opening a webpage, a bookmarklet will run some JavaScript.


How do I create a Bookmarklet?

  1. Create a bookmark in your browser (the same way you would create any bookmark).
  2. Edit the bookmark.
  3. Give it a name to make it easy for you to find.
  4. In the URL field, you are going to add some JavaScript (keep reading to learn what this will look like).


Hard-Coded Template Course

If you would like to add a bookmarklet that will always import the same course, this is the JavaScript code we will use (replace the template_course_id on line 2 with your template course):

// The id of our template course
let template_course_id = '593';
// Only run on the home page of courses without any other content in place (shows import option)
if (ENV.COURSE !== undefined && ENV.COURSE.id !== null && window.location.pathname === '/courses/' + ENV.COURSE.id && $('.ic-EmptyStateList:visible').length > 0) {
// Give user a chance to cancel
let confirmMessage = confirm("This will copy content into your course. Click OK to proceed.");
if (confirmMessage == true) {
// Add a div for feedback
$('#modules_homepage_user_create').prepend('<div id="kl-import-progress" class="alert alert-info"></div>');
// Send request to Canvas
$.post('/api/v1/courses/' + ENV.COURSE.id + '/content_migrations', {'migration_type': 'course_copy_importer', 'settings[source_course_id]': template_course_id}, function(data, textStatus, xhr) {
// Write a response with a link to the course migration page
$('#kl-import-progress').html('Request submitted. Course copy will take a few minutes. Reload this page periodically or <a href="https://community.canvaslms.com/courses/'+ENV.COURSE.id+'/content_migrations">view import progress in Canvas</a>');
});
}
} else {
// Will only work on the course front page
alert('Run this from the course home page of an empty course');
}

In order for this to work as a bookmark, we have to convert it. I like to use MrColes Bookmarklet Creator to convert the code above into what we will add to a bookmark. After converting the code, it will look more like this:

javascript:(function()%7B%2F%2F%20The%20id%20of%20our%20template%20courselet%20template_course_id%20%3D%20'#####'%3B%2F%2F%20Only%20run%20on%20the%20home%20page%20of%20courses%20without%20any%20other%20content%20in%20place%20(shows%20import%20option)if%20(ENV.COURSE%20!%3D%3D%20undefined%20%26%26%20ENV.COURSE.id%20!%3D%3D%20null%20%26%26%20window.location.pathname%20%3D%3D%3D%20'%2Fcourses%2F'%20%2B%20ENV.COURSE.id%20%26%26%20%24('.ic-EmptyStateList%3Avisible').length%20%3E%200)%20%7B%2F%2F%20Give%20user%20a%20chance%20to%20cancellet%20confirmMessage%20%3D%20confirm(%22This%20will%20copy%20content%20into%20your%20course.%20Click%20OK%20to%20proceed.%22)%3Bif%20(confirmMessage%20%3D%3D%20true)%20%7B%2F%2F%20Add%20a%20div%20for%20feedback%24('%23modules_homepage_user_create').prepend('%3Cdiv%20id%3D%22kl-import-progress%22%20class%3D%22alert%20alert-info%22%3E%3C%2Fdiv%3E')%3B%2F%2F%20Send%20request%20to%20Canvas%24.post('%2Fapi%2Fv1%2Fcourses%2F'%20%2B%20ENV.COURSE.id%20%2B%20'%2Fcontent_migrations'%2C%20%7B'migration_type'%3A%20'course_copy_importer'%2C%20'settings%5Bsource_course_id%5D'%3A%20template_course_id%7D%2C%20function(data%2C%20textStatus%2C%20xhr)%20%7B%2F%2F%20Write%20a%20response%20with%20a%20link%20to%20the%20course%20migration%20page%24('%23kl-import-progress').html('Request%20submitted.%20Course%20copy%20will%20take%20a%20few%20minutes.%20Reload%20this%20page%20periodically%20or%20%3Ca%20href%3D%22%2Fcourses%2F'%2BENV.COURSE.id%2B'%2Fcontent_migrations%22%3Eview%20import%20progress%20in%20Canvas%3C%2Fa%3E')%3B%7D)%3B%7D%7D%20else%20%7B%2F%2F%20Will%20only%20work%20on%20the%20course%20front%20pagealert('Run%20this%20from%20the%20course%20home%20page%20of%20an%20empty%20course')%3B%7D%7D)()‍

 It is a lot harder to read but it will do the job. To make things easier for you to update, find the ##### string and replace it with your template course id. Once you update the course id, this is the code that you will paste in as the URL in your bookmark.


Prompt for Course ID

If you want a little more flexibility for what course you want to copy, this option will ask the user to provide a course ID.

Course ID Prompt

Here is the JavaScript we will use for this one (you don't have to update this one):

// Only run on the home page of courses without any other content in place (shows import option)
if (ENV.COURSE !== undefined && ENV.COURSE.id !== null && window.location.pathname === '/courses/' + ENV.COURSE.id && $('.ic-EmptyStateList:visible').length > 0) {
// Prompt user for Canvas course ID
let course = prompt("Please enter the Canvas course ID from which to pull content");
// If they give a response, use it
if (course != null) {
// Placeholder for feedback
$('#modules_homepage_user_create').prepend('<div id="kl-import-progress" class="alert alert-info"></div>');
// Remove any spaces
course = course.trim();
// Send request to Canvas
$.post('/api/v1/courses/' + ENV.COURSE.id + '/content_migrations', {'migration_type': 'course_copy_importer', 'settings[source_course_id]': course}, function(data, textStatus, xhr) {
// Write a response with a link to the course migration page
$('#kl-import-progress').html('Request submitted. Course copy will take a few minutes. Reload this page periodically or <a href="https://community.canvaslms.com/courses/'+ENV.COURSE.id+'/content_migrations">view import progress in Canvas</a>');
});
}
} else {
// Will only work on the course front page
alert('Run this from the course home page of an empty course');
}

And here is that code converted to use for a bookmarklet:

javascript:(function()%7B%2F%2F%20Only%20run%20on%20the%20home%20page%20of%20courses%20without%20any%20other%20content%20in%20place%20(shows%20import%20option)if%20(ENV.COURSE%20!%3D%3D%20undefined%20%26%26%20ENV.COURSE.id%20!%3D%3D%20null%20%26%26%20window.location.pathname%20%3D%3D%3D%20'%2Fcourses%2F'%20%2B%20ENV.COURSE.id%20%26%26%20%24('.ic-EmptyStateList%3Avisible').length%20%3E%200)%20%7B%2F%2F%20Prompt%20user%20for%20Canvas%20course%20IDlet%20course%20%3D%20prompt(%22Please%20enter%20the%20Canvas%20course%20ID%20from%20which%20to%20pull%20content%22)%3B%2F%2F%20If%20they%20give%20a%20response%2C%20use%20itif%20(course%20!%3D%20null)%20%7B%2F%2F%20Placeholder%20for%20feedback%24('%23modules_homepage_user_create').prepend('%3Cdiv%20id%3D%22kl-import-progress%22%20class%3D%22alert%20alert-info%22%3E%3C%2Fdiv%3E')%3B%2F%2F%20Remove%20any%20spacescourse%20%3D%20course.trim()%3B%2F%2F%20Send%20request%20to%20Canvas%24.post('%2Fapi%2Fv1%2Fcourses%2F'%20%2B%20ENV.COURSE.id%20%2B%20'%2Fcontent_migrations'%2C%20%7B'migration_type'%3A%20'course_copy_importer'%2C%20'settings%5Bsource_course_id%5D'%3A%20course%7D%2C%20function(data%2C%20textStatus%2C%20xhr)%20%7B%2F%2F%20Write%20a%20response%20with%20a%20link%20to%20the%20course%20migration%20page%24('%23kl-import-progress').html('Request%20submitted.%20Course%20copy%20will%20take%20a%20few%20minutes.%20Reload%20this%20page%20periodically%20or%20%3Ca%20href%3D%22%2Fcourses%2F'%2BENV.COURSE.id%2B'%2Fcontent_migrations%22%3Eview%20import%20progress%20in%20Canvas%3C%2Fa%3E')%3B%7D)%3B%7D%7D%20else%20%7B%2F%2F%20Will%20only%20work%20on%20the%20course%20front%20pagealert('Run%20this%20from%20the%20course%20home%20page%20of%20an%20empty%20course')%3B%7D%7D)()


Wrap Up

Anyway, I hope that this will be useful to some of you during the present chaos and any future chaos. Feel free to modify, adapt, change, or share that code.

more
3 0 685
Community Member

A long, long time ago, in an office somewhere in my building (I'm guessing), a conversation probably nothing like this took place:

vintage secretary

"Okay, it's time to implement the new LMS, Canvas."

"Hooray! Anything special we need to do?"

"Well, we should probably decide if our Canvas instance should be one big bucket of stuff, or if we need sub-accounts for our 5 separately accredited colleges."

"I'd think sub-accounts by college would be smart!"

"Definitely. Oh... wait... We're integrating Banner with Canvas, right?"

"Of course!"

"Well, we have Banner set up to essentially treat our district as a single entity."

"And?"

"Well, there's no easy way to tell Canvas which sub-account the course should be in."

"Oh. One giant bucket, it is!"

Fast forward a year or two. The transition from Blackboard to Canvas is complete. Faculty adoption is growing rapidly. Online course offerings are expanding. Requests for adding account-level LTIs keep coming. Data and outcomes and analytics are hot topics. People begin to question with more regularity why we don't have sub-accounts to keep these things useful, streamlined, and logical. The answer continues to be "because we don't have Banner set up in a way that makes sub-accounts possible". Fast forward a few more years. People are asking at least weekly why we can't do a thing that can't be done because we don't have college sub-accounts. The requests finally prompt action. The action hits numerous brick walls. There is a script written that seems to solve the problem by moving the courses from the root account to the correct sub-account after the fact. Testing is going well. There is dancing and singing. Then someone performs a section sync in Test Banner, and the course in Test Canvas gets thrown out of its sub-account and back to the root account. Canvas insists that "account" should be sticky. Testing continues to prove that Banner is a jerk and refuses to listen to what Canvas says. Other avenues are considered and defeated. Tears are shed. And here we are, seven long years into our Canvas adventure, without any hierarchy whatsoever. And we've exhausted every reasonable idea, short of demolishing the entire Banner > Middleware > Canvas structure and starting from the ground up.

cartoon guy at computer

So what's the point of my blog post / stream of consciousness rant / discussion prompt / cautionary tale / plea for help? Well, first, my words of advice:

  1. If you are new to Canvas, consider your account/sub-account structure, very very very carefully.
  2. Canvas is a wonderful company full of wonderful people, but they do not have expertise in your SIS of choice, so make sure your SIS of choice is ready and willing to work with you on establishing (and maintaining, and adjusting as needed) a good integration with Canvas.

And my points of discussion:

  1. I know people have created a sub-account structure "after the fact". What makes our situation challenging is the way we set up Banner. We are unable to change how Banner is configured.
  2. We have had various vendors swear they can help us using APIs. This may be true, but they neither understand our Banner setup nor possess actual, practical, deep Canvas knowledge.
  3. We are still using Luminis Message Broker as our middleware. My understanding is that LMB is an outdated tool. But the alternatives (Ethos, ILP) are described to me as not mature enough, not robust enough, and/or possibly not compatible with our current portal (or version of).
  4. We haven't completely ruled out turning off real-time events and doing automated batches. BUT we have a bazillion (actual number) Banner users across our 5 colleges who would need to be re-educated on new processes and that is... daunting.

The plea:

  1. Is there anyone out there that knows Banner really well AND knows Canvas really well AND is not already working full time for a Banner/Canvas institution? We have tried the "hire a consultant" route, and a creature with such expertise (in the land of hire-able consultants) appears to be rarer than a 3-legged unicorn.
  2. Has anyone had a similar situation and come up with a miracle workaround that they'd be willing to share? I will pay you in cookies and a coffee mug that says "You're Awesome!" [side note: don't search Amazon for "You're awesome" coffee mugs. Someone apparently decided not to stop there and made all the mugs NSFW]
  3. Please consider this an open discussion, and throw any ideas into the comments, no matter how wild and insane they might sound. Tag any groups or spaces I missed, or any smart folks who might know something, anything. It's possible there will be points for creativity, but it depends on whether I'm continuing to lose ground in the Community. I once made it to 17th. Those were the days.

Thank you in advance, Canvas friends!

unicorn

Also tagging Canvas DevelopersInstructional DesignersHigher EducationHigher Education SIS

more
6 13 774
Instructure
Instructure

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

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.

more
26 102 21.7K