Go back to the previous page
Move one step back in the session history.
function goBack() { history.back(); }
Usage
history.pushState({ step: 2 }, '', '#step-2');
const popped = new Promise(resolve => addEventListener('popstate', resolve, { once: true }));
goBack();
await popped;
location.hash; // → ''
Know the limits
- history.back() is asynchronous: wait for popstate (same-document entries) or for the page to unload. It does nothing without a previous entry.
- A visible back link still needs a real href, so it works without JavaScript and for visitors who arrived directly.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Go back to the previous page from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Executed in Chromium with a same-document history entry. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.