Await user confirmation in a dialog
Await user confirmation in a dialog in JavaScript: wrap a native dialog element in a promise that resolves true or false. Works in browsers.
window.confirm blocks the page and cannot be styled. A <dialog> element can be, and a small wrapper turns it into something you can await.
function confirmDialog(message) {
const dialog = document.createElement('dialog');
dialog.innerHTML = `
<form method="dialog">
<p></p>
<button value="cancel">Cancel</button>
<button value="ok">OK</button>
</form>`;
dialog.querySelector('p').textContent = message;
document.body.append(dialog);
dialog.showModal();
return new Promise((resolve) => {
dialog.addEventListener(
'close',
() => {
resolve(dialog.returnValue === 'ok');
dialog.remove();
},
{ once: true },
);
});
}
console.log((await confirmDialog('Delete this draft?')) ? 'deleted' : 'kept');deletedThe output is for a click on OK. A button inside <form method="dialog"> closes the dialog and sets returnValue to its value. Pressing Escape closes it without one, so returnValue stays empty and the answer is false, which is the safe default. The message goes in through textContent, so it is never parsed as HTML.
showModal() makes the rest of the page inert while it is open, and gives you focus handling for free. Add a cancel listener if you need to react to Escape specifically.