- local storage is usefull if you code an "offline" mode
- session storage is like bigger domain-restricted cookie
- Attention, web storage data are not crypted. (e.g. players can read/write their scores stored in web storage.)
Code: Select all
Import ""
SetLocalStorage(Key.s, Value.f) As "localStorage.setItem"
GetLocalStorage.f(Key.s) As "localStorage.getItem"
SetLocalStorageString(Key.s, Value.s) As "localStorage.setItem"
RemoveLocalStorage(Key.s) As "localStorage.removeItem"
ClearLocalStorage() As "localStorage.clear"
SetSessionStorage(Key.s, Value.f) As "sessionStorage.setItem"
GetSessionStorage.f(Key.s) As "sessionStorage.getItem"
SetSessionStorageString(Key.s, Value.s) As "sessionStorage.setItem"
RemoveSessionStorage(Key.s) As "sessionStorage.removeItem"
ClearSessionStorage() As "sessionStorage.clear"
EndImport
Procedure.s GetLocalStorageString(Key.s)
!return localStorage.getItem(v_Key) || '';
EndProcedure
Procedure.s GetSessionStorageString(Key.s)
!return sessionStorage.getItem(v_Key) || '';
EndProcedure
Procedure GetLocalStorageKeys(List KeyList.s())
ClearList(KeyList())
!for(var i=0;i<localStorage.length;i++){
Protected key.s
!v_key=localStorage.key(i);
AddElement(KeyList())
KeyList()=key
!} //next
EndProcedure
Procedure.s GetSessionStorageKeys(List KeyList.s())
ClearList(KeyList())
!for(var i=0;i<sessionStorage.length;i++){
Protected key.s
!v_key=sessionStorage.key(i);
AddElement(KeyList())
KeyList()=key
!} //next
EndProcedure
Procedure.i FindLocalStorage(Key.s)
!if (v_Key in localStorage) return 1;
EndProcedure
Procedure.i FindSessionStorage(Key.s)
!if (v_Key in sessionStorage) return 1;
EndProcedure
CompilerIf #PB_Compiler_IsMainFile
; *******************************
; EXAMPLE
; *******************************
;local data will persist even after the browser is closed
If FindLocalStorage("localData")
Debug "localData exists!"+#LF$+"Get localData = "+GetLocalStorageString("localData")+#LF$
Else
SetLocalStorageString("localData","my string value")
Debug "Set localData:"+GetLocalStorageString("localData")+#LF$
EndIf
;session data is also persistent data, however the data is tied to a browsing context (i.e. a browser tab Or window)
If FindSessionStorage("sessionData")
Debug "sessionData exists!"+#LF$+"Get sessionData = "+GetSessionStorage("sessionData")+#LF$
Else
SetSessionStorage("sessionData",1234)
Debug "Set sessionData:"+GetSessionStorage("sessionData")+#LF$
EndIf
NewList Key$()
GetLocalStorageKeys(Key$())
ForEach Key$() : Debug "key:"+Key$() : Next
GetSessionStorageKeys(Key$())
ForEach Key$() : Debug "key:"+Key$() : Next
CompilerEndIf