prettier/website/playground/urlHash.js

36 lines
795 B
JavaScript
Raw Normal View History

2018-04-12 19:27:34 +03:00
import LZString from "lz-string";
export function read() {
const hash = document.location.hash.slice(1);
2018-04-20 17:13:09 +03:00
if (!hash) {
return {};
}
2018-04-19 19:56:10 +03:00
2018-04-12 19:27:34 +03:00
// backwards support for old json encoded URIComponent
const decode =
hash.indexOf("%7B%22") !== -1
? decodeURIComponent
: LZString.decompressFromEncodedURIComponent;
try {
return JSON.parse(decode(hash));
} catch (_) {
return {};
}
}
export function replace(state) {
const hash = LZString.compressToEncodedURIComponent(JSON.stringify(state));
if (
typeof URL === "function" &&
typeof history === "object" &&
typeof history.replaceState === "function"
) {
const url = new URL(location);
url.hash = hash;
history.replaceState(null, null, url);
} else {
location.hash = hash;
}
}