Created
February 22, 2016 05:42
-
-
Save jokester/4a543ea76dbc5ae1bf05 to your computer and use it in GitHub Desktop.
Save and load JSON value with URL hash (aka URL fragment)
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
/** | |
* Save and load JSON value with URL hash (aka URL fragment) | |
* | |
* hash_accessor.load() -> load | |
* hash_accessor.save(obj) -> save serialized obj into hash | |
*/ | |
var hash_accessor = (function (window) { | |
return { | |
load: function () { | |
try { | |
// strip ^# | |
var json_str_escaped = window.location.hash.slice(1); | |
// unescape | |
var json_str = decodeURIComponent(json_str_escaped); | |
return JSON.parse(json_str); | |
} catch (e) { | |
return {}; | |
} | |
}, | |
save: function (obj) { | |
// use replace so that previous url does not go into history | |
window.location.replace('#' + JSON.stringify(obj)); | |
} | |
}; | |
})(window); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment