Article illustration 1

For years, triggering modal dialogs in web applications required imperative JavaScript: developers attached click handlers to buttons that programmatically called showModal() or close() on target elements. Chrome 135 introduces invoker commands—a declarative alternative that eliminates this scripting need. By adding commandfor and command attributes to buttons, developers can now control <dialog> and popover elements directly from HTML.

<button commandfor="my-dialog" command="show-modal">Show Dialog</button>
<dialog id="my-dialog">
  <!-- Dialog content -->
</dialog>

The commandfor attribute references an element's ID (like the for attribute in labels), while command specifies actions mirroring JavaScript methods:
- show-modaldialogEl.showModal()
- closedialogEl.close()
- show-popover/hide-popover/toggle-popover → Popover API equivalents

Beyond built-in commands, developers can define custom actions prefixed with --, handled via the command event:

<button commandfor="confetti" command="--explode">🎉</button>

<script>
  document.getElementById('confetti').addEventListener('command', (e) => {
    if (e.command === "--explode") launchConfetti();
  });
</script>

This approach streamlines common interactions—like opening help dialogs or dismissing notifications—while enhancing accessibility through explicit element relationships. For browsers without native support, a polyfill is available.

Why This Matters: Invoker commands reduce JavaScript bloat for routine tasks, align with HTML's declarative philosophy, and improve maintainability. As modal dialogs and popovers become ubiquitous in modern UIs, this native solution offers a lightweight alternative to framework-specific abstractions. Future expansions could extend command support to additional elements, further empowering HTML-first development.

Source: Chrome Developers