Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

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.

JavaScript
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');
Text
deleted

The 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.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.