How to Detect Back Button Click in Browser
Detecting back button clicks in browsers, especially in web applications that leverage AJAX, presents a challenge. While the window.onbeforeunload event is commonly used for this purpose, it's also triggered on other actions like browser reload, which is undesirable.
Solution:
Fortunately, there's an elegant solution that effectively distinguishes back button clicks from reloads and other events. Here's a modified code that addresses this issue:
<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 clicks here }; } else { // For older browsers that don't support `pushState` var ignoreHashChange = true; window.onhashchange = function () { if (!ignoreHashChange) { ignoreHashChange = true; window.location.hash = Math.random(); // Handle back button clicks here } else { ignoreHashChange = false; } }; } };</code>
This solution works across Chrome and Firefox, providing a more precise way to detect back button clicks while avoiding potential false triggers.
The above is the detailed content of How to Distinguish Back Button Clicks from Browser Reloads and Other Events?. For more information, please follow other related articles on the PHP Chinese website!