Files
test-repo/website/playground/urlHash.js
T

34 lines
783 B
JavaScript
Raw Normal View History

2025-12-30 14:14:17 +08:00
import LZString from "lz-string";
2018-04-12 13:27:34 -03:00
export function read() {
const hash = document.location.hash.slice(1);
2018-04-20 11:13:09 -03:00
if (!hash) {
return {};
}
2018-04-19 13:56:10 -03:00
2026-06-16 02:09:45 +08:00
// backwards support for old JSON encoded URIComponent
2019-11-17 18:06:14 +08:00
const decode = hash.includes("%7B%22")
? decodeURIComponent
: LZString.decompressFromEncodedURIComponent;
2018-04-12 13:27:34 -03:00
try {
return JSON.parse(decode(hash)) ?? {};
} catch {
2018-04-12 13:27:34 -03:00
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;
}
}