Menyembunyikan parameter di URL
dari google https://gist.github.com/ScottKaye/5158488
opo
function persistParams() { const PARAMS_KEY = "__params"; if (performance.navigation.type === performance.navigation.TYPE_RELOAD) { const persistedParams = sessionStorage.getItem(PARAMS_KEY); if (persistedParams) { return persistedParams; } } sessionStorage.setItem(PARAMS_KEY, location.search); return location.search; } function hideParams() { persistParams(); history.replaceState(null, document.title, window.location.pathname); window.addEventListener("beforeunload", () => { history.replaceState( null, document.title, window.location.pathname + (sessionStorage.getItem(PARAMS_KEY) || "") ); }); } window.addEventListener("load", hideParams, false);
pembetulan oleh aiYour code has a scoping error: the variable PARAMS_KEY is declared inside persistParams, making it inaccessible to the hideParams function.To fix this, you should move the constant to the top-level scope so both functions can use it.
javascript// Move the key here so it's shared by all functions
const PARAMS_KEY = "__params";
function persistParams() {
// performance.navigation is deprecated; consider using performance.getEntriesByType("navigation")
if (performance.navigation.type === performance.navigation.TYPE_RELOAD) {
const persistedParams = sessionStorage.getItem(PARAMS_KEY);
if (persistedParams) return persistedParams;
}
sessionStorage.setItem(PARAMS_KEY, location.search);
return location.search;
}
function hideParams() {
persistParams();
// Remove params from address bar immediately
history.replaceState(null, document.title, window.location.pathname);
// Restore params right before the user leaves/reloads
window.addEventListener("beforeunload", () => {
const saved = sessionStorage.getItem(PARAMS_KEY) || "";
history.replaceState(null, document.title, window.location.pathname + saved);
});
}
window.addEventListener("load", hideParams, false);
// Move the key here so it's shared by all functions
const PARAMS_KEY = "__params";
function persistParams() {
// performance.navigation is deprecated; consider using performance.getEntriesByType("navigation")
if (performance.navigation.type === performance.navigation.TYPE_RELOAD) {
const persistedParams = sessionStorage.getItem(PARAMS_KEY);
if (persistedParams) return persistedParams;
}
sessionStorage.setItem(PARAMS_KEY, location.search);
return location.search;
}
function hideParams() {
persistParams();
// Remove params from address bar immediately
history.replaceState(null, document.title, window.location.pathname);
// Restore params right before the user leaves/reloads
window.addEventListener("beforeunload", () => {
const saved = sessionStorage.getItem(PARAMS_KEY) || "";
history.replaceState(null, document.title, window.location.pathname + saved);
});
}
window.addEventListener("load", hideParams, false);
Komentar
Posting Komentar