Skip to content

Instantly share code, notes, and snippets.

@j6k4m8
Last active February 4, 2017 15:54
Show Gist options
  • Save j6k4m8/e09de64fe3847b04c3ce6143d44f319d to your computer and use it in GitHub Desktop.
Save j6k4m8/e09de64fe3847b04c3ce6143d44f319d to your computer and use it in GitHub Desktop.
Use the URL as a backend to store statefulness. Reading from the URL on a subsequent pageload will restore the state as you left it previously.

Usage

DEPRECATED: Use this instead, which is all this and more!!

Say you have a website example.com.

setState('answer', 42);

Your URL is now example.com/?answer=42. No page reload!

getState('answer')  // → '42' (string)
function jsonizeUrl() {
if (window.location.search.length <= 1) {
return {};
}
return JSON.parse('{"' +
decodeURI(
window.location.search.substring(1).replace(/&/g, '","')
.replace(/=/g,'":"')
) + '"}');
}
function getState(key) {
return jsonizeUrl()[key];
}
function setState(key, val) {
var state = jsonizeUrl();
state[key] = val;
window.history.pushState(
null,
document.title,
window.location.origin + window.location.pathname +
'?' + Object.keys(state).reduce((last, key, i) => (
`${last}${i!=0?'&':''}${key}=${state[key]}`
), '')
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment