2

I am working on an application where I want user to continue without clicking back button. I want to prevent them to go back and perform same task again and if they click back button then display a popup message with bootstrap modal.

Here is my code snippet.

function showPopup(url, valid_device) {
  if (window.history && window.history.pushState) {
    $(window).on('popstate', function() {
      $('#bckBtnModal').modal('show');
    });

    $(window).on('DOMContentLoaded', function() {
      $('#bckBtnModal').modal('show');
    });
  }
}

function moveForward(url){
  window.history.pushState( 'forward', null, url );
  history.forward()
}

function checkState(url, valid_device){
  if (window.history && window.history.pushState) {
    window.history.pushState({},'forward', null, url);
    $(window).on('popstate', function() {
      $('#bckBtnModal').modal('show');  
  });
  $(window).on('DOMContentLoaded', function() {
    if(valid_device && show_on_dom_event && push_state_enable){
      $('#bckBtnModal').modal('show');
    }
  });
 }
}

I have used above function like given below:

window.onpageshow = BackBtnHandler.showPopup('/reservations/guest_party_details', '<%= valid_device?%>')
window.onnavigate = BackBtnHandler.moveForward('/reservations/guest_party_details');

But it is not global solution, I found that on OSx chromium browser when page loaded two functions called because it fires two event popstate, DOMContentLoaded while the other most of the browsers either calls popstate or DOMContentLoaded.

I have also tried history.js but didn't get any useful from it.

Anyone have any global solution which works for all major browsers and for all major Operating systems?

Nishant Upadhyay
  • 639
  • 7
  • 20
  • 1
    I don't know the answer, but it seems like something any decent browser would absolutely **not** allow you to do. Maybe consider *why* you need to prevent this behaviour. Is it because the form won't cope with going back? Then detect that and redirect them forward or allow the form to cope. – Steve May 17 '16 at 05:34
  • I have a reservation flow and payment flow in my application, I don't want user to go back and reserve or pay for same thing. BTW Thanks for response. – Nishant Upadhyay May 17 '16 at 05:37
  • There's things you can do to avoid this, perhaps have the form in a modal which won't change the browser history, or open the form in a new tab which will reset the history. – Steve May 17 '16 at 05:38
  • See http://stackoverflow.com/questions/29986657/global-variable-usage-on-page-reload/ – guest271314 May 17 '16 at 06:03

0 Answers0