Home > Web Front-end > JS Tutorial > body text

How to Distinguish Back Button Clicks from Browser Reloads and Other Events?

Susan Sarandon
Release: 2024-10-22 12:42:02
Original
192 people have browsed it

How to Distinguish Back Button Clicks from Browser Reloads and Other Events?

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!