Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách vô hiệu hóa nút Back (quay lại) của trình duyệt với JavaScript

Cảnh báo: Vô hiệu hóa nút Back là anti-pattern, vi phạm UX, accessibility, và có thể bị trình duyệt chặn. Chỉ dùng trong trường hợp đặc biệt (ngân hàng, thanh toán, quiz) và phải có fallback.

Kỹ thuật history manipulation

<!DOCTYPE html>
<html>
<head>
  <title>Disable Browser Back Button</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <a href="newpage.html">Trang tiếp theo</a>
  <script>
    $(document).ready(function() {
      function disableBack() { window.history.forward(); }
      window.onload = disableBack;
      window.onpageshow = function(evt) { if (evt.persisted) disableBack(); };
      // Hoặc dùng History API hiện đại
      history.pushState(null, null, location.href);
      window.addEventListener('popstate', function() {
        history.pushState(null, null, location.href);
      });
    });
  </script>
</body>
</html>

Giải thích

  • history.pushState(null, null, location.href) thêm entry mới vào history stack.
  • Sự kiện popstate fire khi user nhấn Back/Forward.
  • Trong handler, pushState lại đẩy user về trang hiện tại.
  • evt.persisted (PageShowEvent) xử lý bfcache (back-forward cache).

Hạn chế & Rủi ro

  • Không hoạt động nếu user nhấn giữ nút Back → chọn lịch sử.
  • Chrome/Firefox có thể chặn pushState lặp trong popstate.
  • Vi phạm WCAG 2.1: 3.2.2 On Input (Unexpected change of context).
  • Làm hỏng trải nghiệm: user không thể quay lại trang trước legitimately.

Giải pháp thay thế tốt hơn

  • Warn before unload: beforeunload event hỏi xác nhận.
  • Form state persistence: Lưu draft vào localStorage/IndexedDB, khôi phục khi quay lại.
  • Multi-step form trong một trang: Dùng DOM show/hide hoặc SPA routing thay vì load trang mới.