Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>SPA Style History API Example</title> </head> <body> <h1>Page Navigation with History API</h1> <div id="content">Start Page</div> <!-- Buttons for navigation --> <button onclick="loadPage('page1')">Load Page 1</button> <button onclick="loadPage('page2')">Load Page 2</button> <button onclick="manualGoBack()">Go Back</button> <button onclick="manualGoForward()">Go Forward</button> <!-- Display the current status of the history --> <p id="historyStatus">History Status: Start</p> <script> // Loads a "page" and updates the browser's history state function loadPage(page) { const state = { page: page }; // State to be pushed to history history.pushState(state, `Page ${page}`, `${page}.html`); // Pushing state to the history document.getElementById('content').innerHTML = `<h2>This is ${page.replace('page', 'Page ')}</h2>`; // Update the content updateHistoryStatus(state); // Update the history status display } // Handles the browser's back and forward button actions window.onpopstate = function(event) { if (event.state) { // Update the page content and history status when navigating through history document.getElementById('content').innerHTML = `<h2>This is ${event.state.page.replace('page', 'Page ')}</h2>`; updateHistoryStatus(event.state); } else { // Fallback content when the history does not have any state document.getElementById('content').innerHTML = `<h2>Start Page</h2>`; document.getElementById('historyStatus').textContent = "History Status: Start"; } }; // Updates the display of the current history status function updateHistoryStatus(state) { document.getElementById('historyStatus').textContent = `History Status: ${state.page}`; } // Function to manually trigger going back in history function manualGoBack() { history.back(); } // Function to manually trigger going forward in history function manualGoForward() { history.forward(); } </script> </body> </html>