How to customize the Javascript's confirm() box

confirm, javascript

Solution

There are only specific messages/buttons you can offer the user, without using a custom alert box/plugin. They are:

To display a message with just an OK button, by calling:

window.alert('Message');

To display a message with OK/Cancel as the options, by calling:

var didTheyPressOK = window.confirm('Are you sure you want to XXXXX?');

As StackOverflow does in your example, to display a Leave.../Stay... message on leaving the page, where pressing Stay causes the browser to stay on your page (the exact button wording is browser-dependent, you cannot control it):

window.onbeforeunload = function() {
    // you may or may not want a condition here, e.g.
    // if (thereAreUnsavedChanges)
    return 'Are you sure you actually want to leave? You have unsaved changes...';
}

For any other situation, you'll need to use some kind of alert plugin (or write one yourself :-/), as you speculated in your question.

Put simply, those buttons are browser specific and chrome automatically displays helpful text on the button to make things clearer. It happens with `window.onbeforeunload` if you return a string, which is displayed as a message before navigation.

Problem

How does stackoverflow customize the `confirm()` box's buttons and add custom text to the buttons? All the other questions I looked at pointed at a random `jQuery` plugin to do this. Can this be done with Vanilla Javascript? If yes, then how?

Original source

Related problems