


How to Distinguish Back Button Clicks from Browser Reloads and Other Events?
Oct 22, 2024 pm 12:42 PMHow 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

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

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial

8 Stunning jQuery Page Layout Plugins

Improve Your jQuery Knowledge with the Source Viewer

10 Mobile Cheat Sheets for Mobile Development
