Skip to content

Instantly share code, notes, and snippets.

@jokester
Created February 22, 2016 05:42
Show Gist options
  • Save jokester/4a543ea76dbc5ae1bf05 to your computer and use it in GitHub Desktop.
Save jokester/4a543ea76dbc5ae1bf05 to your computer and use it in GitHub Desktop.
Save and load JSON value with URL hash (aka URL fragment)
/**
* 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