Files
test-repo/website/playground/urlHash.js
T
fisker Cheung 57f0dd56dd Replace indexOf with includes (#6967)
* Replace `indexOf` with `includes`

* Add `unicorn/prefer-includes`
2019-11-17 11:06:14 +01:00

35 lines
781 B
JavaScript

import LZString from "lz-string";
export function read() {
const hash = document.location.hash.slice(1);
if (!hash) {
return {};
}
// backwards support for old json encoded URIComponent
const decode = hash.includes("%7B%22")
? 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;
}
}