When attempting to detect back button clicks, developers often rely on the window.onbeforeunload event listener. However, this event triggers not only for back button clicks but also for browser reloads, which can be misleading.
Detecting Back Button Clicks without Browser Reload Interference
To handle back button clicks without false positives, consider using a tailored approach:
History Modification:
Hash-Based Approach:
Implementation
<code class="javascript">window.onload = function () { if (typeof history.pushState === "function") { history.pushState("jibberish", null, null); window.onpopstate = function () { history.pushState('newjibberish', null, null); // Handle back button click here }; } else { var ignoreHashChange = true; window.onhashchange = function () { if (!ignoreHashChange) { ignoreHashChange = true; window.location.hash = Math.random(); // Handle back button click here } else { ignoreHashChange = false; } }; } }</code>
Compatibility
This approach has been reported to work effectively in Chrome and Firefox.
The above is the detailed content of How to Detect User\'s Back Button Click in Browsers Without Browser Reload Interference?. For more information, please follow other related articles on the PHP Chinese website!