63 lines
2.0 KiB
JavaScript
63 lines
2.0 KiB
JavaScript
|
|
/**
|
||
|
|
* Back Button Navigation Control - SIMPLIFIED & FIXED
|
||
|
|
*
|
||
|
|
* Problem: History manipulation (replaceState/pushState) changes URL without reloading page
|
||
|
|
* Solution: Let browser handle navigation naturally, only intercept when necessary
|
||
|
|
*
|
||
|
|
* Requirements:
|
||
|
|
* 1. Natural browser back/forward navigation (URL changes = page loads)
|
||
|
|
* 2. Prevent going back past home page
|
||
|
|
* 3. Ensure page is always interactive after navigation
|
||
|
|
*/
|
||
|
|
|
||
|
|
(function () {
|
||
|
|
"use strict";
|
||
|
|
|
||
|
|
// Configuration
|
||
|
|
const HOME_PAGES = ["/", "/home.html", "/index.html"];
|
||
|
|
const HOME_URL = "/home.html";
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Handle popstate (back/forward button) events
|
||
|
|
* This fires AFTER the browser has already navigated (URL changed)
|
||
|
|
*/
|
||
|
|
function handlePopState(event) {
|
||
|
|
// Get the NEW current path (browser already changed it)
|
||
|
|
const currentPath = window.location.pathname;
|
||
|
|
|
||
|
|
// Ensure page is always interactive after back/forward
|
||
|
|
document.body.classList.remove("page-transitioning");
|
||
|
|
document.body.style.opacity = "1";
|
||
|
|
sessionStorage.removeItem("page-transitioning");
|
||
|
|
|
||
|
|
// If we're on home page after a back navigation
|
||
|
|
// prevent going back further by adding home to history
|
||
|
|
if (HOME_PAGES.includes(currentPath)) {
|
||
|
|
// Use setTimeout to avoid interfering with current popstate
|
||
|
|
setTimeout(() => {
|
||
|
|
window.history.pushState({ page: "home" }, "", HOME_URL);
|
||
|
|
}, 0);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Prevent going back past home page
|
||
|
|
* Add an extra entry so back button stays on home
|
||
|
|
*/
|
||
|
|
function preventBackPastHome() {
|
||
|
|
const currentPath = window.location.pathname;
|
||
|
|
if (HOME_PAGES.includes(currentPath)) {
|
||
|
|
// Add an extra home entry
|
||
|
|
window.history.pushState({ page: "home", initial: true }, "", HOME_URL);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Initialize: Add home history entry if on home page
|
||
|
|
preventBackPastHome();
|
||
|
|
|
||
|
|
// Listen for popstate (back/forward button)
|
||
|
|
// NOTE: Browser handles the actual navigation (page reload)
|
||
|
|
// We just ensure interactivity and prevent going back past home
|
||
|
|
window.addEventListener("popstate", handlePopState);
|
||
|
|
})();
|