JavaScript before leaving the page

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

    Just a bit more helpful, enable and disable

    $(window).on('beforeunload.myPluginName', false); // or use function() instead of false
    $(window).off('beforeunload.myPluginName');
    
    0 讨论(0)
  • 2020-11-22 08:39

    You can use the following one-liner to always ask the user before leaving the page.

    window.onbeforeunload = s => "";
    

    To ask the user when something on the page has been modified, see this answer.

    0 讨论(0)
  • 2020-11-22 08:46
    <!DOCTYPE html>
    <html>
    <body onbeforeunload="return myFunction()">
    
    <p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
    
    <a href="https://www.w3schools.com">Click here to go to w3schools.com</a>
    
    <script>
    function myFunction() {
        return "Write something clever here...";
    }
    </script>
    
    </body>
    </html>
    

    https://www.w3schools.com/tags/ev_onbeforeunload.asp

    0 讨论(0)
  • 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 = '';
        }
    
    });
    
    0 讨论(0)
提交回复
热议问题