<p>beforeunload happend before unload. beforeunload can give user a message, asking user if want to contine or not, if yes, unload event will trigger and unload can show user a message, but can not block to unload the page. Below is the sample.</p>

        <pre data-sub="prettyprint:_">
        // Attach to the beforeunload handler
        window.onbeforeunload = function(){
        // Return an explanation for why the user should not leave the page.
        return 'Your data will not be saved.';
        };

        // Watch for the user leaving the web site
        window.onunload = function(){
        // Display a message to the user, thanking them for visiting
        alert( 'Thanks for visiting!' );
        };

        </pre>