How to Use the window.confirm() API
The confirm()
API provided by browsers allows us to ask for user confirmation before performing certain actions. This widely supported API has been around since the early days of the Web and can be a handy tool in various scenarios without the need for a custom-built user interface.
To use the confirm()
API, simply call the function and pass a string representing the confirmation message that you want to display to the user. Here’s an example:
1 | confirm("Are you sure you want to delete this element?"); |
When the confirm()
function is called, a confirmation dialog box is shown to the user. The appearance of this dialog box may vary slightly depending on the browser being used, but the basic concept remains the same.
For instance, in Chrome, the confirmation dialog box looks like this:
In Safari, it looks like this:
And in Firefox, it looks like this:
Note that although the recommended way to call confirm()
is window.confirm()
, you can omit the window
part, as it is implicit.
Once the confirmation dialog box is displayed, the browser suspends script execution until the user clicks either the OK or Cancel button. It is not possible to bypass this without clicking one of the buttons.
The confirm()
function returns a boolean value: true
if the user clicks OK, or false
if the user clicks Cancel. You can assign this value to a variable or use it directly in a conditional statement. Here are a couple of examples:
1 | const confirmed = confirm("Are you sure you want to delete this element?"); |
1 | if (confirm("Are you sure you want to delete this element?")) { |
Using the confirm()
API can enhance the user experience by providing a simple way to prompt for user confirmation before taking important actions.
tags: [“JavaScript”, “confirm()”, “user confirmation”, “browser API”]