Music Software Development

Web MIDI API guide

The Web MIDI API lets a web page talk to MIDI devices: keyboards, drum pads, synthesizers, interfaces and virtual ports. It gives you lists of inputs and outputs, delivers incoming messages as byte arrays, and sends bytes with optional timestamps. It does not make sound (use Web Audio for that), read files, or speak MIDI 2.0. It is MIDI 1.0 bytes in and out.

This guide covers everything a real app needs: support and permissions, access, ports, receiving, timestamped sending, hot-plugging, closing and error handling. Every code block comes from one module that the site’s tests run against simulated ports. The live monitor on this page uses the same module.

Browser support (as of December 2026)

BrowserWeb MIDINotes
Chrome, Edge, Opera and other Chromium-based desktop browsersYesPermission prompt for all MIDI access, not only sysex
Chrome on AndroidYesWhich USB or Bluetooth devices appear depends on Android and the device
Firefox desktopYes, since version 108Access is granted through a site-permission prompt that Firefox implements as an add-on install
Firefox for AndroidNo
Safari on macOSNo native supportThird-party extensions exist; do not assume your users have one
Safari and other browsers on iPhone and iPadNoiOS browsers use WebKit, which does not implement Web MIDI

This table summarises MDN and caniuse compatibility data available in December 2026. Support changes, so check caniuse.com/midi before you rely on a specific version. In code, detect the feature instead of checking the browser name, and give unsupported browsers something useful, such as importing and exporting MIDI files:

if (!('requestMIDIAccess' in navigator)) {
  // Not supported (e.g. Safari) or not a secure context: offer file import/export instead.
}

Secure context, permission and iframes

<iframe src="https://tools.example/editor" allow="midi"></iframe>

Requesting access and handling errors

export class MidiUnavailableError extends Error {
  name = 'MidiUnavailableError';
}

/** Requests MIDI access, or throws MidiUnavailableError when the API is missing. */
export async function getMidiAccess({ sysex = false, nav = globalThis.navigator } = {}) {
  if (typeof nav?.requestMIDIAccess !== 'function') {
    throw new MidiUnavailableError(
      globalThis.isSecureContext === false
        ? 'Web MIDI needs a secure context: load the page over HTTPS or from http://localhost.'
        : 'This browser does not provide the Web MIDI API. Try a current Chrome, Edge or Firefox on desktop.',
    );
  }
  return nav.requestMIDIAccess({ sysex });
}

/** Turns a rejection from requestMIDIAccess into advice a user can act on. */
export function explainMidiError(error) {
  switch (error?.name) {
    case 'MidiUnavailableError':
      return error.message;
    case 'NotAllowedError': // current spec and browsers
    case 'SecurityError': // older spec text and implementations
      return 'MIDI access was blocked. Allow MIDI for this site in the browser’s site settings, then try again.';
    case 'NotSupportedError':
      return 'This system cannot provide MIDI with the requested options (for example sysex).';
    case 'InvalidStateError':
      return 'The operating system’s MIDI service reported an error. Reconnect the device or restart the browser.';
    case 'AbortError':
      return 'The MIDI request was interrupted. Reload the page and try again.';
    default:
      return 'MIDI could not start: ' + (error?.message ?? String(error));
  }
}
FailureTypical causeWhat to tell the user
requestMIDIAccess is undefinedUnsupported browser, insecure page, or an iframe without allow="midi"Which browsers work, or offer a non-MIDI fallback
NotAllowedError or SecurityErrorThe user (or a policy) denied the permission, or denied it earlier and the browser rememberedHow to re-allow MIDI in the site settings
NotSupportedErrorThe system cannot provide the requested options (for example sysex)Try again without sysex, or on another system
InvalidStateErrorThe operating system’s MIDI service failedReconnect the device or restart the browser
AbortErrorThe request was interrupted, for example by navigationTry again

Browsers and specification versions have used both NotAllowedError and SecurityError for a denied permission, so handle both. Do not retry in a loop: after a denial, browsers typically reject immediately until the user changes the site setting.

Listing inputs and outputs

access.inputs and access.outputs are map-like objects keyed by port id. Each port has these properties:

/** Plain-object snapshot of every port, for display or logging. */
export function listPorts(access) {
  const info = (p) => ({ id: p.id, name: p.name, manufacturer: p.manufacturer, state: p.state, connection: p.connection });
  return { inputs: [...access.inputs.values()].map(info), outputs: [...access.outputs.values()].map(info) };
}

/**
 * Listens to every input, including devices plugged in later.
 * onMessage(data: Uint8Array, timeStamp: number, input) runs once per complete message.
 * Returns a function that stops listening and closes the inputs.
 */
export function watchInputs(access, onMessage, onChange = () => {}) {
  const attach = (input) => {
    input.onmidimessage = (event) => onMessage(event.data, event.timeStamp, input); // also opens the port
  };
  access.inputs.forEach(attach);
  access.onstatechange = (event) => {
    const { port } = event;
    if (port.type === 'input' && port.state === 'connected' && !port.onmidimessage) attach(port);
    onChange(port);
  };
  return () => {
    access.onstatechange = null;
    access.inputs.forEach((input) => {
      input.onmidimessage = null;
      input.close();
    });
  };
}

A device with several jacks appears as several ports, and names are not unique. Show the name to the user, but store the id. If a remembered id is missing, fall back to the name, then ask the user.

Receiving messages

Setting onmidimessage opens the port and starts delivery. If you use addEventListener('midimessage', …) instead, call input.open() yourself. Each event carries:

Decode the bytes with the message parser. Two kinds of message flood a naive log:

Filter them unless you need them. Sysex messages are delivered only if access was granted with sysex: true.

Sending with timestamps

output.send(data, timestamp) takes complete messages and an optional timestamp in the performance.now() timebase. Without a timestamp, or with one in the past, the message goes out immediately. A future timestamp lets the browser and the operating system deliver the message on time, even if your main thread is busy then. This is the MIDI counterpart of scheduling Web Audio ahead.

/** Schedules a note on an output. Timestamps are in the performance.now() timebase (milliseconds). */
export function playNote(output, { note = 60, velocity = 100, channel = 1, durationMs = 500, at = performance.now() } = {}) {
  const ch = channel - 1; // 0–15 on the wire
  output.send([0x90 | ch, note, velocity], at);
  output.send([0x80 | ch, note, 0], at + durationMs);
}

/** "Panic": sustain off, All Sound Off (CC 120) and All Notes Off (CC 123) on all 16 channels. */
export function panic(output) {
  for (let ch = 0; ch < 16; ch++) {
    output.send([0xb0 | ch, 64, 0]);
    output.send([0xb0 | ch, 120, 0]);
    output.send([0xb0 | ch, 123, 0]);
  }
}
const access = await navigator.requestMIDIAccess({ sysex: true });
output.send([0xf0, 0x7e, 0x7f, 0x06, 0x01, 0xf7]);   // Universal Identity Request
// Without sysex permission, sending F0 throws an InvalidAccessError.

Hot-plugging: the statechange event

When a device is connected or disconnected, access.onstatechange fires with event.port. It also fires when a port’s connection changes, for example when you open it. The watchInputs helper above attaches a handler to any input that appears later, and lets the UI refresh its lists. When a device returns, look up the user’s saved port id again rather than holding on to the old object. A disconnected output’s send() may throw an InvalidStateError, so wrap user-triggered sends in try/catch.

Closing

Set onmidimessage = null and call port.close() on ports you no longer need. There is no method to release the MIDIAccess object itself. Drop your references, and the browser closes everything when the page unloads. On some operating systems, an open port can block other applications from using the same device, so close ports when your app is idle or in the background.

Live MIDI monitor

The monitor needs JavaScript.

The monitor runs entirely in your browser and sends nothing unless you press a send button. Each line shows the arrival time, the input, the raw bytes in hex and the decoded message. If it reports that Web MIDI is unavailable or blocked, the Web MIDI section of the troubleshooting guide explains why.

Using the module in your page

Copy web-midi-monitor.mjs and midi-message.mjs into your project. The monitor also imports a note-name helper from this site’s MIDI library. Copy that too, or replace the import with your own function. Then wire the module to a button:

import { getMidiAccess, explainMidiError, listPorts, watchInputs, playNote } from './web-midi-monitor.mjs';
import { describeMessage } from './midi-message.mjs';

button.addEventListener('click', async () => {
  let access;
  try {
    access = await getMidiAccess();             // permission prompt appears here
  } catch (error) {
    status.textContent = explainMidiError(error);
    return;
  }
  console.table(listPorts(access).inputs);
  watchInputs(access, (data) => console.log(describeMessage(data)));
  const output = access.outputs.values().next().value;
  if (output) playNote(output, { note: 60, durationMs: 300 });
});

Testing without hardware

Libraries

If you would rather work with note names and events than with bytes, WEBMIDI.js (Apache-2.0) wraps this API. For a comparison with native options, see music software SDKs. For what the bytes mean, see MIDI messages in bytes. When devices don’t show up or notes stick, see MIDI troubleshooting.