0

The subject is pretty much says it all. I would like to display another div if the user decides to stay on the page. Is there an event I can listen for if they refuse page navigation?

I found this here, Detecting whether user stayed after prompting onBeforeUnload But I can't get this to work at all. I don't "own" the buttons that are displayed, so I can't monitor clicks, or can I?

Community
  • 1
  • 1
Lazloman
  • 1,289
  • 5
  • 25
  • 50
  • Specifics would help. How do you not "own" the HTML you're working on? You can attach an event listener to any element on a page if it's there. You can also delegate listening to outer containers for elements that get swapped out or added later (see event delegation or event bubbling). iframes that share the same domain can also be accessed. – Erik Reppen May 06 '13 at 23:04
  • 1
    Possible duplicate with a good answer: [Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?](http://stackoverflow.com/questions/4650692/way-to-know-if-user-clicked-cancel-on-a-javascript-onbeforeunload-dialog?rq=1) – metadings May 06 '13 at 23:55
  • Let me clarify, onbeforeunload displays a dialog box with two buttons. One allows the user to continue to a another site, the other allows the user to remain on the current page. Since the browser displays that dialog box, I don't have a reference to the buttons, therefore I can't know which one has been clicked. – Lazloman May 07 '13 at 13:41

1 Answers1

2

It is not possible to tell whether the OK or the Cancel button was clicked beacuse, like you said, you do not "own" it.

With that being said, there is a trick that theoretically should work. If the user clicks cancel, then the onunload event will never be executed and everything stays as it was before the popup was executed. If the OK button is clicked, however, the onunload event will be executed. So, the theory is: you can figure out if the user clicked OK if the onunload event was executed. The problem with this is that there isn't much you can do in the onunload event because at that point, it is unstoppable.

So, for a definitive answer to your question: No. The typical onunload event that is fired after the onbeforeunload event will not be fired if the user clicks cancel.

Brian
  • 529
  • 2
  • 7
  • 17