You cannot block the user from leaving the page. What you can do is warn them by asking if they want to leave or not.
The window.onbeforeunload event should return a string (and only a string). This line will be printed in the notification window made by the browser.
You cannot use your own notification field or block a user from exiting (or redirecting).
window.onbeforeunload = function(){ return 'Are you sure you want to leave?'; };
Or using jQuery
$(window).on('beforeunload', function(){ return 'Are you sure you want to leave?'; });
When the user leaves the page, you can use the onunload event to call AJAX ( async: false may be required here).
Example:
$(window).unload(function(){ $.ajax({ url: '/path/to/page/', async: false,
NOTE. Instead, why don't you just save everything when the user is completed? Instead of saving it and then deleting if the user is not finished?
source share