Home  >  Article  >  Web Front-end  >  How to Accurately Detect Back Button Clicks in Web Browsers While Avoiding False Triggers?

How to Accurately Detect Back Button Clicks in Web Browsers While Avoiding False Triggers?

Susan Sarandon
Susan SarandonOriginal
2024-10-22 14:43:54685browse

How to Accurately Detect Back Button Clicks in Web Browsers While Avoiding False Triggers?

Detecting Back Button Click in Web Browsers: Addressing False Triggers

When attempting to detect a user's back button click, developers often rely on the window.onbeforeunload event. However, this approach has a limitation: it also triggers when other actions are performed, such as refreshing the page.

A more comprehensive solution is to differentiate between back button clicks and other events:

Using History API:

This approach targets browsers that support the History API (history.pushState function):

<code class="js">window.onload = function () {
  if (typeof history.pushState === "function") {
    history.pushState("jibberish", null, null);
    window.onpopstate = function () {
      history.pushState('newjibberish', null, null);
      // Handle back or forward button clicks here (excluding refresh)
    };
  } else {
    ... // Handle non-History API browsers
  }
}</code>

Using Hash Changes:

For browsers without History API support, a fallback solution can be implemented using hash changes:

<code class="js">window.onload = function () {
  ... // Similar to History API code
} else {
  var ignoreHashChange = true;
  window.onhashchange = function () {
    if (!ignoreHashChange) {
      ignoreHashChange = true;
      window.location.hash = Math.random();
      // Detect back button click here
      // Note: Messes with hash symbol at the end of URL
    } else {
      ignoreHashChange = false;
    }
  };
}</code>

Handling Refresh Issue:

While the above solutions address back button detection, they do not handle refreshing the page. For this, window.onbeforeunload can still be used:

<code class="js">window.onbeforeunload = function (e) {
  if (e.preventDefault) {
    e.preventDefault();
    e.returnValue = '';
  }
}</code>

The above is the detailed content of How to Accurately Detect Back Button Clicks in Web Browsers While Avoiding False Triggers?. 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