how to detect browser back and forward button clicks using Java Script

This code demonstrates how to detect browser back and forward button clicks using the History API and custom events. When the user interacts with the back or forward button, the corresponding custom event is fired, allowing you to handle specific actions in your application


<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Browser Back & Forward Identification</title>

</head>

<body>

    <button id="btn"> <a href="#title">Click the link to change the URL</a></button>

    <h2 id="title">How to detect browser back and forward button clicks</h2>

    <p class="result"></p>

    <script>

if(window.history && history.pushState){ // check for history api support

window.addEventListener('load', function(){

// create history states

history.pushState(-1, null); // back state

history.pushState(0, null); // main state

history.pushState(1, null); // forward state

history.go(-1); // start in main state

this.addEventListener('popstate', function(event, state){

// check history state and fire custom events

if(state = event.state){

event = document.createEvent('Event');

event.initEvent(state > 0 ? 'next' : 'previous', true, true);

this.dispatchEvent(event);

// reset state

history.go(-state);

}

}, false);

}, false);

}


window.addEventListener('next', function(){

console.log('forward button clicked');

 }, false);

 

 window.addEventListener('previous', function(){

  console.log('back button clicked');

 }, false);

</script>

</body>

</html>


Here is the code explanation : 

  1. HTML Structure:

    • The provided code snippet is an HTML document. It defines a simple webpage with a button and a heading.
    • The <button> element contains an anchor link (<a>) with the text “Click the link to change the URL.”
    • The <h2> element has the title “How to detect browser back and forward button clicks.”
  2. JavaScript Logic:

    • The code checks if the browser supports the History API (specifically, the pushState and popstate methods).
    • If the History API is supported, it proceeds with the following steps:
  3. Creating History States:

    • Three history states are created using history.pushState():
      • -1 represents the back state (i.e., when the user clicks the browser’s back button).
      • 0 represents the main state (initial state when the page loads).
      • 1 represents the forward state (i.e., when the user clicks the browser’s forward button).
    • The history.go(-1) call ensures that the initial state is set to the main state.
  4. Handling the popstate Event:

    • The popstate event is triggered when the user navigates the session history (e.g., by clicking the back or forward button).
    • Inside the popstate event listener:
      • It checks the history state (stored in the event.state variable).
      • If the state is positive (greater than 0), it dispatches a custom event called 'next'.
      • If the state is negative (less than 0), it dispatches a custom event called 'previous'.
      • The custom events allow you to handle specific actions based on whether the user clicked the back or forward button.
      • Finally, it resets the state by navigating back (using history.go(-state)).
  5. Custom Event Listeners:

    • Two custom event listeners are defined:
      • When the 'next' event is triggered (i.e., the forward button is clicked), it logs “forward button clicked” to the console.
      • When the 'previous' event is triggered (i.e., the back button is clicked), it logs “back button clicked” to the console.
  6. Summary:

    • This code demonstrates how to detect browser back and forward button clicks using the History API and custom events. When the user interacts with the back or forward button, the corresponding custom event is fired, allowing you to handle specific actions in your application.

Comments

Popular posts from this blog

DACPAC Pros & Cons

Understanding Asynchronous JavaScript