Created
January 18, 2017 11:18
-
-
Save gustavoapolinario/a3df8421c46a20bffed18479c3992029 to your computer and use it in GitHub Desktop.
Gerencia registros salvando-os no navegador (localStorage ou Cookie)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
/* | |
* Class myStorage | |
* Gerencia registros salvando-os no navegador | |
* Suporte a cookie e localStorage | |
*/ | |
var myStorage = new Object(); | |
myStorage.defaultExpirationDays = 30; | |
myStorage.getCookie = function(name) { | |
if (document.cookie.length > 0) { | |
var start = document.cookie.indexOf(name + "="); | |
if (start != -1) { | |
start = start + name.length + 1; | |
var end = document.cookie.indexOf(";", start); | |
if (end == -1) { | |
end = document.cookie.length; | |
} | |
return unescape(document.cookie.substring(start, end)); | |
} | |
} | |
return ""; | |
} | |
myStorage.setCookie = function(name, value, expirationDays) { | |
if( typeof expirationDays == 'undefined' ) { | |
expirationDays = myStorage.defaultExpirationDays; | |
} | |
var d = new Date(); | |
d.setTime(d.getTime() + (expirationDays*24*60*60*1000)); | |
var expires = "expires="+ d.toUTCString(); | |
document.cookie = name + "=" + value + ";" + expires + ";path=/"; | |
} | |
/* | |
* usa os localStorage/cookies para gerenciar os registros. | |
* Necessário para caso o navegador não suporte o localStorage (IE lt 7) | |
*/ | |
myStorage.getItem = function(name) { | |
if( myStorage.testLocalStorage() ) { | |
localStorage.getItem(name); | |
} | |
else { | |
myStorage.getCookie(name); | |
} | |
} | |
myStorage.setItem = function(name, value) { | |
if( myStorage.testLocalStorage() ) { | |
localStorage.setItem(name, value); | |
} | |
else { | |
myStorage.setCookie(name, value); | |
} | |
} | |
/* | |
* function testLocalStorage | |
* verifica se o navegador suporta localStorage | |
*/ | |
myStorage.testLocalStorage = function() { | |
return typeof localStorage !== 'undefined'; | |
} | |
/* | |
* Class myStorage | |
* Gerencia registros salvando-os no navegador | |
* Suporte a cookie e localStorage | |
*/ | |
var myStorage = new Object(); | |
;(function() { | |
var nivelUsuario = myStorage.getItem('nivelUsuario'); | |
if( nivelUsuario == "" ) { | |
$.ajax('http://jsonplaceholder.typicode.com/posts', { | |
method: 'GET', | |
data: { | |
total: 1 | |
} | |
}).then(function(data) { | |
console.log(data); | |
nivelUsuario = data | |
myStorage.setItem('nivelUsuario', nivelUsuario); | |
}); | |
} | |
if( nivelUsuario != "" ) { | |
ga('set', 'nivelUsuario', nivelUsuario ); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment