JavaScript to pull student name and ID from Canvas into Storyline

Feb 14, 2024

Per the title, can anyone advise on the JavaScript code needed to get a student's name and ID from the Canvas?

3 Replies
Math Notermans

This is overly complicated Peter. As a student is logged in into Canvas LMS there is no need for using the Canvas API. The easy solution is this.

You just need a few variables in your Storyline. That's all.

//some variables needed
var pathArray,myName,newName;

var player = GetPlayer();

function findLMSAPI(win) {
if (win.hasOwnProperty("GetStudentID")) {
            return win;
    }else if (win.parent == win) {
        return null;
    }else {
        return findLMSAPI(win.parent);
    }
}

function getUsersName(){

console.log("getUsersName");

pathArray = window.location.pathname.split('/');
console.log("pathArray[2]: "+pathArray[2]+" | "+window.location.pathname+" | "+pathArray[1]);
     //&& pathArray[1] !="review" => true if it is not on Storyline Review, so a real LMS
if (pathArray[2] != undefined && pathArray[2] !="Users" && pathArray[1] != "review" && pathArray[1] != "rise"){
  // when published as Scorm  on a LMS
  var lmsAPI = findLMSAPI(this);
  myName = lmsAPI.GetStudentName();
  var array = myName.split(',');
  newName = array[1] + ' ' + array[0];
  player.SetVar("newuser", newName);
  console.log("pathArray[2]: "+pathArray[2]+" / "+myName+" | "+newName);
  // on a LMS
  //pathArray[2]: instructure.canvas.com / SPACE_Notermans,Math
}else{
 // locally testing or not on a LMS
 console.log("NOT ON A LMS!, so use a demo user");
 player.SetVar("newuser", 'User,Demo');
 myName = "User,Demo";
 newName = "Demo User";
}
}

getUsersName();

There is in fact one other thing to watch when getting the users name from Instructure Canvas. Canvas adds a space in front of the users name. So Canvas returns a string starting with a space. Good to be aware of.

Working sample added.