JavaScript before leaving the page

前端 未结 10 1768
谎友^
谎友^ 2020-11-22 08:01

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload

<         


        
10条回答
  •  死守一世寂寞
    2020-11-22 08:34

    This what I did to show the confirmation message just when I have unsaved data

    window.onbeforeunload = function () {
                if (isDirty) {
                    return "There are unsaved data.";
                }
                return undefined;
            }
    

    returning "undefined" will disable the confirmation

    Note: returning "null" will not work with IE

    Also you can use "undefined" to disable the confirmation

    window.onbeforeunload = undefined;
    

提交回复
热议问题