Home  >  Article  >  Web Front-end  >  How to Distinguish Back Button Clicks from Browser Reloads and Other Events?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-22 12:42:02193browse

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>

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!

Statement:
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