Web History API

Navigate and manipulate browser history with JavaScript

🕰️ What is the History API?

The History API allows you to manipulate the browser's session history - the pages the user has visited. You can add, modify, or navigate through history entries without refreshing the page.


// Get current page info
console.log("Current URL:", window.location.href);
console.log("History length:", history.length);

// Go back one page
history.back();

// Go forward one page  
history.forward();
                                    

Output:

Current URL: https://example.com/page.html

History length: 5

Navigation commands executed

History API Methods

⬅️

history.back()

Go to previous page

history.back()
➡️

history.forward()

Go to next page

history.forward()
🎯

history.go()

Go to specific page

history.go(-2)

pushState()

Add new history entry

history.pushState()

🔹 Basic Navigation

Simple navigation using the History API:

<button onclick="goBack()">← Back</button>
<button onclick="goForward()">Forward →</button>
<button onclick="goToPage()">Go 2 Pages Back</button>

<script>
function goBack() {
    // Go back one page
    history.back();
}

function goForward() {
    // Go forward one page
    history.forward();
}

function goToPage() {
    // Go back 2 pages
    history.go(-2);
    
    // Go forward 1 page
    // history.go(1);
    
    // Refresh current page
    // history.go(0);
}

// Check if we can go back
if (history.length > 1) {
    console.log("Can navigate back");
}
</script>

Navigation Demo:

🔹 Adding History Entries

Use pushState() to add new entries to browser history:

// Add a new history entry
function addHistoryEntry(page) {
    const state = { page: page, timestamp: Date.now() };
    const title = `Page ${page}`;
    const url = `?page=${page}`;
    
    history.pushState(state, title, url);
    updatePageContent(page);
}

// Update page content without refresh
function updatePageContent(page) {
    document.getElementById('content').innerHTML = `
        <h2>Page ${page}</h2>
        <p>This is page ${page} content</p>
        <p>URL changed without page refresh!</p>
    `;
}

// Handle browser back/forward buttons
window.addEventListener('popstate', function(event) {
    if (event.state) {
        updatePageContent(event.state.page);
        console.log('Navigated to:', event.state.page);
    }
});

Single Page App Demo:

Content would update here without page refresh

🔹 Replacing History Entries

Use replaceState() to modify the current history entry:

// Replace current history entry
function replaceCurrentPage(newPage) {
    const state = { page: newPage, replaced: true };
    const title = `Updated Page ${newPage}`;
    const url = `?page=${newPage}&updated=true`;
    
    history.replaceState(state, title, url);
    console.log('Current entry replaced');
}

// Example: Update URL when form is submitted
function handleFormSubmit() {
    const formData = new FormData(document.getElementById('myForm'));
    const searchTerm = formData.get('search');
    
    // Replace current URL with search parameters
    const newUrl = `?search=${encodeURIComponent(searchTerm)}`;
    history.replaceState({ search: searchTerm }, 'Search Results', newUrl);
    
    // Show search results
    displaySearchResults(searchTerm);
}

// Check current state
function getCurrentState() {
    const currentState = history.state;
    if (currentState) {
        console.log('Current state:', currentState);
    } else {
        console.log('No state data');
    }
}

Replace State Example:

pushState(): Adds new entry (can go back)

replaceState(): Replaces current entry (can't go back to old)

Use replaceState() for search results, form submissions

🔹 Complete SPA Example

Here's a simple Single Page Application using the History API:

<nav>
    <a href="#" onclick="navigateTo('home')">Home</a>
    <a href="#" onclick="navigateTo('about')">About</a>
    <a href="#" onclick="navigateTo('contact')">Contact</a>
</nav>

<div id="app-content">
    <h1>Welcome to Home Page</h1>
</div>

<script>
// Page content
const pages = {
    home: '<h1>Home Page</h1><p>Welcome to our website!</p>',
    about: '<h1>About Us</h1><p>Learn more about our company.</p>',
    contact: '<h1>Contact</h1><p>Get in touch with us.</p>'
};

// Navigate to a page
function navigateTo(page) {
    // Update content
    document.getElementById('app-content').innerHTML = pages[page];
    
    // Update URL and history
    history.pushState({ page: page }, page, `/${page}`);
}

// Handle browser back/forward
window.addEventListener('popstate', function(event) {
    if (event.state && event.state.page) {
        document.getElementById('app-content').innerHTML = pages[event.state.page];
    }
});
</script>

SPA Navigation:

Content updates here without page refresh

URL changes, browser back/forward works!

🧠 Test Your Knowledge

Which method adds a new entry to browser history?