I've got an onbeforeunload event working that pops up a dialog box warning users about unsaved changes to a form when they navigate away.
window.onbeforeunload = function() {
return 'You have unsaved changes.';
};
How do I customize the dialog box that shows up so it's a little more user friendly. Right now it's rather unwieldy:
"Are you sure you want to navigate away from this page?
You have unsaved changes.
Press OK to continue, or Cancel to stay on the current page."
I notice that Stack Overflow has one that is much cleaner: "You have started writing or editing a post", and the buttons say "Stay on this page", "Leave this page" instead of a generic "Cancel" and "OK". How can I do that?
I am using jQuery, if that's necessary for the solution.
You can't set a custom message on a modern browser instead you can use of default alert function. Save this answer. Show activity on this post. Save this answer.
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.
The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.
Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.
Browsers don't let you customize this box at all. The only reason it would look different on SO is because you were using a different browser when you accessed it. Google Chrome uses buttons labeled 'Stay on this page' and 'Leave this page'. Based on the example text you posted, it looks like you tested your onbeforeunload
handler using Internet Explorer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With