Detect Back Button Click in Browser
To track user navigation events, the window.onbeforeunload event listener can be employed. However, this event triggers not only when the back button is pressed but also during page refresh or reload.
Solution:
To resolve this issue, the following code utilizing the window.onload event can be used:
window.onload = function () { if (typeof history.pushState === "function") { history.pushState("jibberish", null, null); window.onpopstate = function () { history.pushState('newjibberish', null, null); // Handle back/forward navigation here }; } else { var ignoreHashChange = true; window.onhashchange = function () { if (!ignoreHashChange) { ignoreHashChange = true; window.location.hash = Math.random(); // Handle hash change navigation here } else { ignoreHashChange = false; } }; } }
This solution distinguishes between back navigation and other events like refresh and reloads, offering precise handling of back button clicks. It operates smoothly in browsers such as Chrome and Firefox.
The above is the detailed content of How Can You Detect Back Button Clicks in a Browser?. For more information, please follow other related articles on the PHP Chinese website!