Providing a custom message when a user leaves a window without saving data

Can someone provide me with a special alert field that says “you are about to leave the page and the changes will be discarded” Yes / No.

I tried using the following code, but it gave me a default message saying that "Your changes cannot be saved"

here is my javascript code

unsaved=true;
window.onbeforeunload = function() { 
    if (unsaved) 
    { 
        var _message = "You currently have unsaved changes!!!\n\nAre you sure you want to exit without saving.\n\nChoose ‘Leave this page’ to exit without saving changes.\nChoose ‘Stay on this page’ to return to the billing profile."; 
        return _message; 
    } 
}

I also do not have a form, but a simple button that I cannot include in the form by clicking on this button, and this gives me a warning. Here is the Fiddle so that any help is truly appreciated thanks to you. I know that there are questions asked on this topic before, but believe me, now no one is working. update there are some methods described in previous StackOverflow examples, but now they do not work in modern browsers.

+4
source share
2 answers

There is a method in JavaScript called window.confirm (): https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm

if (window.confirm("Question"))
  console.log('clicked OK');
else
  console.log('clicked cancel');
0
source

Try this jQuery

$(window).bind('beforeunload', function(){
  return 'Your message here';
});

Javascript

window.onbeforeunload = function(){
  return 'Your message here';
};
0

Source: https://habr.com/ru/post/1652188/


All Articles