Forum Discussion
Share variables between two different sotryline files using javascript
I would really appreciate an explanation of how to do this.
Hi GarrisonWilliam this script should do it. Copy this into your Master Slide so that the script is available throughout your project.
window.rebusmedia = {
StorylinePlayer : GetPlayer(),
getSLCookie : function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
},
setSLCookie : function(name,value,days) {
days = (days ? days : 999);
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/; SameSite=None; Secure";
},
getSharerdVar : function(sharedVarName)
{
// try and get value from a stored cookie
const val = this.getSLCookie(sharedVarName);
// update the value in Storyline
if(val !== null) this.StorylinePlayer.SetVar(sharedVarName, val);
},
setSharerdVar : function(sharedVarName)
{
// get value from Storyline
const value = this.StorylinePlayer.GetVar(sharedVarName);
// set the value in a cookie
this.setSLCookie(sharedVarName, value);
}
}
You can then call the following JavaScript function to Get and Set the shared variables between the two Storyline modules (on the same domain):
window.rebusmedia.setSharerdVar("UserName");
This will execute JavaScript that will then retrieve the value of a Storyline variable called UserName from the current Storyline module. So, as an example, you have an input box for the users name. You might then have a trigger in Storyline that executes the above JavaScript, like this:
You could use the following JavaScript:
window.rebusmedia.getSharerdVar("UserName");
To try and and retrieve an existing "UserName" and determine whether to show the input box for the user. The getSharerdVar function will only populate the Storyline variable, if the value is not null. So, if it is the first time the user enters the module, the "UserName" variable would remain empty, as their is not a cookie storing the data, therefore, we could show the user name input box, after the script has executed, but if "UserName" is no longer empty, we can assume an existing UserName cookie value has been located and populated the one in storyline.
This is one example of usage.
Three important points:
- The content has to be on the same domain, as the cookies are domain specific
- You must ensure the On restart player property is set to Always resume
- The pages must be run via an internet/intranet as setting cookies does not work on your local file system, for example your C: drive.