JavaScript before leaving the page

前端 未结 10 1769
谎友^
谎友^ 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:47

    Most of the solutions here did not work for me so I used the one found here

    I also added a variable to allow the confirm box or not

    window.hideWarning = false;
    window.addEventListener('beforeunload', (event) => {
        if (!hideWarning) {
            event.preventDefault();
            event.returnValue = '';
        }
    
    });
    

提交回复
热议问题