Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize onbeforeunload dialog box

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.

like image 377
keithjgrant Avatar asked Jan 06 '11 17:01

keithjgrant


People also ask

Is it possible to display a custom message in the Beforeunload popup?

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.

What triggers Onbeforeunload?

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.

What is Onbeforeunload in JS?

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.

How do you cancel Windows Onbeforeunload?

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.


1 Answers

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.

like image 129
Alex Vidal Avatar answered Nov 03 '22 23:11

Alex Vidal