How to use the History API in HTML5?
Use history.pushState() to add new history and update the URL without refreshing the page. It is suitable for maintaining navigation when dynamic content changes in a single-page application; 2. By listening to popstate events, restore the corresponding page status when the user clicks the forward or back button; 3. Use history.replaceState() to modify the current history instead of adding it, suitable for updating the URL without adding the history stack; 4. Best practices include ensuring that the server supports routing, checking API availability, avoiding cross-domain URLs, and using meaningful state objects; 5. Examples show that page jumps and history management are implemented through encapsulation functions, combining pushState and popstate to achieve smooth client routing, thereby building a single-page application with complete browser navigation support.

The History API in HTML5 allows you to manipulate the browser's session history — the pages visited in the current tab or window — without triggering a full page reload. This is especially useful for building single-page applications (SPAs) where you want to update the URL and support navigation (like back/forward buttons) while dynamically changing content.

Here's how to use the key features of the History API effectively.
1. Understanding history.pushState()
Use pushState() to add a new entry to the browser's history stack and update the URL without reloading the page.

Syntax:
history.pushState(state, title, url);
-
state: An object containing data associated with the new history entry (can be retrieved later). -
title: Currently ignored by most browsers (you can pass an empty string). -
url: The new URL to display (must be of the same origin).
Example:

// Change URL to /page2 and add to history
history.pushState({ page: "page2" }, "", "/page2");
// You can now update the page content dynamically
document.body.innerHTML = "<h1>Page 2</h1>";Now, when the user clicks the back button, they'll return to the previous state.
2. Handling the popstate Event
When the user navigates through history (eg, using back/forward buttons), the popstate event is fired. You need to listen for this event to restore the appropriate content.
window.addEventListener("popstate", function(event) {
if (event.state) {
// Restore content based on the state object
document.body.innerHTML = `<h1>You are on ${event.state.page}</h1>`;
} else {
document.body.innerHTML = "<h1>Home Page</h1>";
}
}); Note: popstate only fires when navigating between entries created by pushState() or replaceState() , not after pushState() itself.
3. Using history.replaceState()
Unlike pushState() , replaceState() modify the current history entry instead of adding a new one.
Use case: You want to update the URL after some client-side processing without creating an extra step in history.
// Update current history entry to /updated-page
history.replaceState({ page: "updated" }, "", "/updated-page");This is useful when you want to clean up or modify the URL after form submission or filtering.
4. Best Practices and Tips
- Always handle back/forward navigation : Make sure your
popstatelistener updates the UI appropriately. - Don't rely on URL-only changes : Since the server isn't involved, ensure your app can handle direct visits to these URLs via server-side routing (eg, using a catch-all route in SPAs).
- Check for API support :
if (window.history && window.history.pushState) { // Safe to use History API } - Avoid cross-origin URLs : The
urlparameter must be same-origin, or an error will be thrown. - Use meaningful state objects : Store minimum but useful data (like page ID or view type) to help restore the UI later.
5. Example: Simple SPA Navigation
function navigationTo(url, pageTitle, content) {
const state = { url, content };
history.pushState(state, pageTitle, url);
document.title = pageTitle;
document.body.innerHTML = `<h1>${content}</h1>`;
}
// Simulate navigation
navigateTo("/about", "About", "About Us");
// Handle back/forward
window.addEventListener("popstate", function(event) {
if (event.state) {
document.title = event.state.url;
document.body.innerHTML = `<h1>${event.state.content}</h1>`;
} else {
document.body.innerHTML = "<h1>Home</h1>";
}
});This gives smooth navigation with working browser buttons.
Basically, the History API gives you control over the address bar and navigation flow — essential for modern web apps. Just remember to sync your UI with the history state and handle both programming and user-triggered navigation.
The above is the detailed content of How to use the History API in HTML5?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20516
7
13630
4
How to quickly create a virtual human explanation video with Synthesia_Synthesia virtual human video production guide [Quick]
Dec 18, 2025 pm 06:54 PM
Synthesia can quickly generate high-quality virtual human explanation videos: 1. Select a virtual human and customize the voice intonation; 2. Paste the script to enable automatic lip synchronization; 3. Add dynamic backgrounds and graphic and text layers; 4. Generate multi-language versions in batches with one click; 5. Export MP4 or embed HTML5 code for publication.
What to do if the IE browser web page loads slowly? IE browser performance optimization
Jan 15, 2026 pm 02:21 PM
Optimization methods for slow loading of IE web pages include: 1. Disable non-essential add-ons; 2. Reset IE settings; 3. Adjust connection and advanced parameters; 4. Clean system temporary files and DNS cache; 5. Turn off hardware acceleration and set to standard document mode.
Quark Browser video cannot be played. Steps to troubleshoot Quark Browser playback problems.
Jan 22, 2026 am 09:30 AM
Solutions to abnormal video playback in Quark browser include: 1. Check network connection and access permissions; 2. Clear cache and website data; 3. Enable JavaScript and H5 playback support; 4. Switch to desktop version of UA; 5. Turn off hardware acceleration and reset media services.
3699 mini-games online play entrance, latest decompression mini-games updated daily
Jan 13, 2026 pm 02:12 PM
The entrance address for online play of 3699 mini games is https://www.3699.com. The platform is based on HTML5 technology and runs without plug-ins. It supports multi-terminal adaptation, CDN acceleration, preloading optimization, and decompressed games are updated daily, classified according to emotional dimensions, and taking into account both interaction friendliness and privacy and security protection.
What to do if Microsoft Edge video clarity is blurred Microsoft Edge image quality adjustment
Jan 04, 2026 am 10:24 AM
Edge video blur can be enabled by enabling VSR, using the enhancement button, configuring NVIDIARTX overclocking, turning off hardware acceleration or checking DRM restrictions. The corresponding solution needs to be selected based on the graphics card model, browser version and video encryption.
What should you pay attention to when collecting Shenma search on the mobile terminal? Tips for adapting to the mobile terminal [Instructions]
Jan 04, 2026 am 11:00 AM
In order to improve the inclusion effect of Shenma Search mobile terminal, it is necessary to adopt independent adaptation (self-jumping), add mobile-agentMeta statement, submit corresponding Sitemap for PC and mobile pages, ensure that the basic quality of mobile pages meets the standards, and verify the effective status of adaptation.
Browser browser high-definition rendering version address browser browser organ network high-definition rendering version clearly presented
Dec 20, 2025 am 09:30 AM
The address of browser browser HD rendering version is https://www.browser-hd-render.com, which features 4K sharp rendering, HDR video playback, Brotli compression optimization, end-to-end encrypted synchronization and accessibility auxiliary functions.
How to set full-screen mode in uc browser_Steps to set full-screen mode in uc browser [Compilation]
Jan 14, 2026 pm 09:27 PM
There are five ways to solve the problem that UC Browser cannot go full screen: 1. Turn on the full screen switch through the toolbox; 2. Add UC smart components in the settings; 3. Switch UA to the computer version and refresh the page; 4. Use the F11 key or double-click the video and other system-level operations; 5. Clear the web page and GPU cache and then restart.





