3

I need a way to disable browser back button or show popup for going back when the user is on 2nd page of gravity form or already have POST data available.

Suppose form is on https://www.example.com/form/ and it has 3 steps. On step 1, if user submits data, it stays on /form/ page but the content it shows is from step-2 of form. On this stage, I want to disable the back button or ask user if he wants to go back but it will erase the submitted data of step-1.

I have tried with popstate and it does disable back button on first visit/ or first step of form when we do not have any POST data (when user visits from example.com/page/ to exmaple.com/form/ and tries to go back, it can not)

    window.addEventListener('popstate', function (event) {
        alert(event.state);
        history.pushState(null, null, document.URL);
    });  

On using this code, alert shows null but it does stop from going back if it is normal visit (without POST data) but I need a way to stop going back if the form data is submitted

I have also tried with the following code:


    window.addEventListener('DOMContentLoaded', function(eventX){
    console.log("DOMContentLoaded done!");
      setTimeout(function(){
           console.log("beforeunload registered");
        window.onbeforeunload = function(){return backDisable()};
        window.addEventListener("beforeunload", function(){return backDisable();});

      },1000);

    });
function backDisable()
{
  return "show some warning here!";
} 

I have set delay to let other stuff gets load. This script works fine if user tries to visit another page on website and it shows popup if user wants to leave the page but it is also showing popup if user submits the form on step-1 or step-2 (i can sort it out) but back button on browser still works.

Adeel Ahmed
  • 39
  • 1
  • 3

1 Answers1

0

Try to use window.history.forward() method or onbeforeunload and return alert for users in javascript for more details check this question (how to stop browser back button using javascript)

Milad
  • 328
  • 1
  • 11
  • I have already tried onbeforeunload and it does not get register. tried with window.onbeforeunload and also with window.addEventListener – Adeel Ahmed Mar 23 '19 at 12:38
  • Did you check it with window.history.forward() ? it should be work check this website for this method [link](https://www.encodedna.com/2014/07/restrict-or-disable-browser-back-button-using-javascript.htm) – Milad Mar 23 '19 at 13:37
  • Yes, I did.. no hope – Adeel Ahmed Mar 23 '19 at 14:50