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

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

Susan Sarandon
Release: 2024-10-22 14:43:54
Original
683 people have browsed it

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

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

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

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!

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!