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)
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]}` | |
), '') | |
); | |
} |