showModal Opens The Native dialog Element

dialog.showModal opens a native modal in the top layer, and a form with method=dialog closes it while writing the submitter button value into returnValue.

JavascriptForm Validation

Code

javascriptsnippet
20 lines
// <dialog> native modal: showModal renders in the top layer, Esc closes it, and clicks cannot pass through to the page
const dialog = document.createElement('dialog');
dialog.innerHTML =
  '<form method="dialog">' +
  '<button value="approve">Approve</button>' +
  '<button value="reject">Reject</button>' +
  '</form>';
document.body.append(dialog);

dialog.showModal();
console.log('open after showModal:', dialog.open);

// form method="dialog": submitting closes the dialog; requestSubmit's submitter argument puts the button value into returnValue
dialog.querySelector('form').requestSubmit(dialog.querySelector('button'));
console.log('after submit:', dialog.open, '| returnValue:', dialog.returnValue);

// close(reason) closes explicitly and writes returnValue; Esc fires a cancel event and closes the same way
dialog.showModal();
dialog.close('timeout');
console.log('after close :', dialog.open, '| returnValue:', dialog.returnValue);

Inside the snippet

Module-level bindings hold the data — dialog — with no function scope in between.

What to watch for

  • Uses document, so it needs a browser context — it will not run as-is in Node without shims.

Putting it to use

Look for the open after showModal:, after submit:, after close : prefixes when the file runs; they tie each line to its step.

Core lines

dialog.querySelector('form').requestSubmit(dialog.querySelector('button'));
const dialog = document.createElement('dialog');
'<button value="approve">Approve</button>' +
'<button value="reject">Reject</button>' +
'</form>';

Interactive Tools for This Topic

FAQ

Does showModal Opens The Native dialog Element run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.