Created
November 2, 2011 15:28
-
-
Save nuxlli/1333934 to your computer and use it in GitHub Desktop.
Fallback to localStorage in Samsung Smart TV
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
/** | |
* 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; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.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
to