Prompt User before browser close?

后端 未结 4 759
灰色年华
灰色年华 2020-12-05 08:08

We have an administrative portal that our teachers constantly forget to download their latest PDF instructions before logging out and/or closing the browser window. I have l

相关标签:
4条回答
  • 2020-12-05 08:31

    You cannot alert or things like that in onbeforeunload, you cannot simply return false to make the user not leave the page, as with other events like onclick. This would allow a site to make it impossible to leave it.

    You can however just return a string, the browser then shows a confirm dialog including your string asking the user whether they really want to leave.

    0 讨论(0)
  • 2020-12-05 08:32

    I think that this may be part of your problem:

    else if(window.onbeforeunload) {
      window.onbeforeunload = unloadMess;
    };
    

    That test in the "if" statement will only be true if there's already a handler function. That test doesn't mean, "does the window object have an 'onbeforeunload' property?". It means, "is the 'onbeforeunload' property of the window currently not null?".

    I think it'd be safe to just set "onbeforeunload" directly, for any browser.

    0 讨论(0)
  • 2020-12-05 08:46

    Update 2017

    All modern browsers do not support custom messages any longer.

    window.onbeforeunload = function(evt) {
       return true;
    }
    

    This one for closing the tab:

    window.onbeforeunload = function(evt) {
        var message = 'Did you remember to download your form?';
        if (typeof evt == 'undefined') {
            evt = window.event;
        }
        if (evt) {
            evt.returnValue = message;
        }
    
        return message;
    }
    

    and use onClick event for logout button:

    onClick="return confirm('Did you remember to download your form?');"
    
    0 讨论(0)
  • 2020-12-05 08:47

    Pointy is right about browser close events - imagine if evil sites could prevent you from closing their windows?? So you cannot prevent them from closing your site, but you can do an alert.

    As far as your logout button is concerned, that is much more straight-forward:

    <a href="logout.html" onClick="return confirm('Did you remember to download your form?');">Logout</a>
    
    0 讨论(0)
提交回复
热议问题