Capturing result of window.onbeforeunload confirmation dialog

眉间皱痕 提交于 2019-11-27 23:40:23
Haochi

You can have the exit confirmation using window.onbeforeunload but there isn't a way to find out which button the user clicked on.

To quote an earlier response from jvenema from this thread:

The primary purpose for the beforeunload is for things like allowing the users the option to save changes before their changes are lost.

Besides, if your users are leaving, it's already too late [...]

How about this:

$( window ).bind( 'beforeunload' , function( event ) {
    setTimeout( function() {
        alert( 'Hi againe!' );
    } );
    return '';
} ).bind( 'unload', function( event ) {
    alert( 'Goodby!' );
} );

Late to the party, but I found the following code (in TypeScript) to be a decent way to detect if the person clicked on 'Ok' on that confirmation dialogue window.

public listenToUnloadEvents(): void {

  window.addEventListener('beforeunload', (e) => {
    const confirmationMessage = '\o/';

    (e || window.event).returnValue = confirmationMessage;     // Gecko + IE
    return confirmationMessage;                                // Webkit, Safari, Chrome etc.
  });

  window.addEventListener('unload', () => {

    this.sendNotification(Action.LEFT)
  });
}

I'm not sure how much time you have to run code in the unload event, but in this instance, I am sending a notification through Socket.io, so it's very quick at completing.

As for detecting the cancel on that notification, as someone else mentioned, creating a global variable like let didEnterBeforeUnload = false could be set to true when the beforeunload event fires. After this, by creating the third event, like so (again, in TypeScript), you can infer the user pressing cancel

window.addEventListener('focus', (e) => {

  if (didEnterBeforeUnload) {
    console.log('pressed cancel')
  }

  didEnterBeforeUnload = false
});

As a side-note though, these events won't (iirc) fire unless you have interacted with the page. So make sure to click or tap into the page before trying to navigate away during your testing.

I hope this helps anyone else out there!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!