How can I override the OnBeforeUnload dialog and replace it with my own?

前端 未结 11 2186
一生所求
一生所求 2020-11-21 06:14

I need to warn users about unsaved changes before they leave a page (a pretty common problem).

window.onbeforeunload=handler

This works bu

11条回答
  •  没有蜡笔的小新
    2020-11-21 07:03

    While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.

    I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/

    $(':input').change(function() {
        if(!is_dirty){
            // When the user changes a field on this page, set our is_dirty flag.
            is_dirty = true;
        }
    });
    
    $('a').mousedown(function(e) {
        if(is_dirty) {
            // if the user navigates away from this page via an anchor link, 
            //    popup a new boxy confirmation.
            answer = Boxy.confirm("You have made some changes which you might want to save.");
        }
    });
    
    window.onbeforeunload = function() {
    if((is_dirty)&&(!answer)){
                // call this if the box wasn't shown.
        return 'You have made some changes which you might want to save.';
        }
    };
    

    You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.

    I have cut out code, so this may not work as is.

提交回复
热议问题