Skip to content

Instantly share code, notes, and snippets.

@nuxlli
Created November 2, 2011 15:28
Show Gist options
  • Save nuxlli/1333934 to your computer and use it in GitHub Desktop.
Save nuxlli/1333934 to your computer and use it in GitHub Desktop.
Fallback to localStorage in Samsung Smart TV
/**
* Fallback to localStorage
**/
;(function() {
if (typeof localStorage == "undefined" && typeof FileSystem == "function") {
var fileSyObj = new FileSystem();
var fileName = curWidget.id + "_localStorage.db";
var lStorage = {};
var changed = false;
// load or init localStorage file
var fileObj = fileSyObj.openCommonFile(fileName, "r+");
if (fileObj != null) {
try {
lStorage = JSON.parse(fileObj.readAll());
} catch(e) { }
} else {
fileObj = fileSyObj.openCommonFile(fileName, "w")
fileObj.writeAll("{}");
}
fileSyObj.closeCommonFile(fileObj);
// Save storage
lStorage.saveFile = function(delay) {
if (changed && typeof JSON == 'object') {
var $self = this;
var save = function() {
fileObj = fileSyObj.openCommonFile(fileName, "w")
fileObj.writeAll(JSON.stringify($self));
fileSyObj.closeCommonFile(fileObj);
changed = false;
}
if (typeof delay != 'undefined' && delay)
setTimeout(save, 100);
else
save();
}
}
lStorage.setItem = function(key, value) {
changed = true;
this[key] = value;
this.saveFile(true);
return this[key];
}
lStorage.getItem = function(key) {
return this[key];
}
window.localStorage = lStorage;
}
})();
@alexmnv
Copy link

alexmnv commented Feb 19, 2016

There's a slight difference between native localStorage and this implementation.
In native localStorage all values are stored as strings, while in this implementation the values keep their original type.

// native:
localStorage.setItem('test', 1);
localStorage.getItem('test'); // string '1'

// this implementation:
localStorage.setItem('test', 1);
localStorage.getItem('test'); // number 1

This might seem insignificant, but I had a very tricky bug related to that.
In order to fix that you need to change the line

this[key] = value;

to

this[key] = value.toString();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment