1

Iv been trying to figure out the best way to do this without much luck. I would like to do something if the user clicks back such as showing a custom dialog.

I have tried this which works to a certain extend:

var url = 'www.examples.com';
history.pushState(
    {
        pushStateUrl: url
    },
    url,
    url
);
window.onpopstate = function() {
    showDialog();
};

But it doesnt feel clean as it involves manipulating the browser history. Is there any better way to detect back without changing the history.

p.s. it does not have to work in all browsers. And preferably not using jquery.

Also beforeunload does not work in my case as I cannot show my own custom dialog.

strangeQuirks
  • 4,761
  • 9
  • 40
  • 67

2 Answers2

0
    this is a late response but I am posting in the intention of this could help to someone like me
    add **beforeunload** event lister for your page when loaded
    and remove it when submitting the form or  whenever you want

     step 1: var stayOnPage =function(){
 confirm("Would you like to save this draft?");
          if (!stayOnPage) {
            history.back() or
     // do your stuff
          } else {
           // do your stuff
          }
    }

     window.addEventListener('beforeunload',stayOnPage);


    step 2: remove event listener when you want

    function onSubmitForm(){
        window.removeEventListener('beforeunload',stayOnPage);
    }

    <button onclick="onSubmitForm()"> Submit </button>



    if this doesn't work 

    change beforeunload to popstate 
    i.e

    function onSubmitForm(){
       window.addEventListener('popstate', stayOnPage);
    }
Ramusesan
  • 854
  • 2
  • 11
  • 32
-1

Try this and it's found here

window.onbeforeunload = onBack;
function onBack(evt)
{
if (evt == undefined)
    evt = window.event;  
if (    (evt.clientX < 0) || 
    (evt.clientY < 0) || 
    (evt.clientX > document.body.clientWidth) ||
    (evt.clientY > document.body.clientHeight)
    )
{
    alert('Unload from browser button press');
    return "You clicked some browser button? Do you want to move away from this page?";
}
return undefined;

}
jusola
  • 29
  • 6