Skip to content

Instantly share code, notes, and snippets.

@Danny-Driscoll

Danny-Driscoll/setLocalStorage.js Secret

Last active Apr 17, 2019
Embed
What would you like to do?
var minBrowserVersions = {"safari":12.1,"ff":67.0};
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return false;
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function setLocalStorageFromCookie(){
var value = {
id: getCookie("optimizelyEndUserId"),
set_time: Date.now()
};
var string_value = JSON.stringify(value);
localStorage.setItem("optimizelyEndUserId",string_value);
}
function checkBrowserVersion(minVersions){
var curBrowser = optimizely.get('visitor').browserId;
var curVersion = parseFloat(optimizely.get('visitor').browserVersion);
if(minBrowserVersions[curBrowser] && curVersion >= minBrowserVersions[curBrowser]){
console.log('Included browser');
return true;
}
else{
console.log('not applicable');
}
}
function onActivated(){
var matchingBrowser = checkBrowserVersion(minBrowserVersions);
if(matchingBrowser){
setLocalStorageFromCookie();
}
};
function checkForAndSetId(cookieName){
if(!getCookie(cookieName) && typeof localStorage.getItem(cookieName) != "undefined"){
var value = JSON.parse(localStorage.getItem(cookieName));
setCookie('optimizelyEndUserId',value.id,7);
}
else{
window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
type: "addListener",
filter: {
type: "lifecycle",
name: "activated"
},
handler: onActivated
});
}
}
checkForAndSetId("optimizelyEndUserId");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment