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)
| Browser | Web MIDI | Notes |
|---|---|---|
| Chrome, Edge, Opera and other Chromium-based desktop browsers | Yes | Permission prompt for all MIDI access, not only sysex |
| Chrome on Android | Yes | Which USB or Bluetooth devices appear depends on Android and the device |
| Firefox desktop | Yes, since version 108 | Access is granted through a site-permission prompt that Firefox implements as an add-on install |
| Firefox for Android | No | |
| Safari on macOS | No native support | Third-party extensions exist; do not assume your users have one |
| Safari and other browsers on iPhone and iPad | No | iOS 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
- Secure context.
navigator.exists only on pages served over HTTPS or fromrequestMIDIAccess http://localhost. On plain HTTP it is simplyundefined. - Permission. Chrome used to prompt only for sysex. Starting with Chrome 124 (rolled out gradually), it asks before granting any MIDI access. Firefox also asks. Call
requestMIDIAccess()from a button click, so the prompt appears when the user expects it, and explain beforehand why you need it. - Sysex (system exclusive, used for patch dumps and firmware) needs
{ sysex: true }and a stronger prompt. Request it only if you need it. Some users will refuse. - Iframes. MIDI is controlled by the
midiPermissions Policy feature. A cross-origin iframe needsallow="midi":
<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));
}
}
| Failure | Typical cause | What to tell the user |
|---|---|---|
requestMIDIAccess is undefined | Unsupported browser, insecure page, or an iframe without allow="midi" | Which browsers work, or offer a non-MIDI fallback |
NotAllowedError or SecurityError | The user (or a policy) denied the permission, or denied it earlier and the browser remembered | How to re-allow MIDI in the site settings |
NotSupportedError | The system cannot provide the requested options (for example sysex) | Try again without sysex, or on another system |
InvalidStateError | The operating system’s MIDI service failed | Reconnect the device or restart the browser |
AbortError | The request was interrupted, for example by navigation | Try 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:
id: save it to remember the user’s choice.nameandmanufacturer.type:"input"or"output".state:"connected"or"disconnected".connection:"open","closed"or"pending".
/** 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:
event.data: aUint8Arrayholding one complete message, already split for you (no running status).event.timeStamp: the arrival time in the same millisecond timebase asperformance.now().
Decode the bytes with the message parser. Two kinds of message flood a naive log:
- Clock (
F8), 24 times per beat when a device sends sync. - Active Sensing (
FE), several times per second from some keyboards.
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]);
}
}
- Data must be complete, valid messages. Running status and stray data bytes throw a
TypeError. - Sending sysex (
F0 … F7) without sysex permission throws anInvalidAccessError. - To play MIDI in sync with Web Audio, convert audio-clock times with
getOutputTimestamp(). - The specification defines
output.clear()to drop queued messages, but browser support has been inconsistent. A “panic” like the one above is the reliable way to silence a device. Remember that Note Offs you have already queued will still be sent.
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.
Inputs: none found
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
- Virtual ports. macOS has the IAC Driver (Audio MIDI Setup). On Linux, software synths and ALSA virtual MIDI devices show up as ports. On Windows, use a DAW or a virtual-port utility.
- Fake ports in unit tests. Every helper here takes its dependencies as arguments:
getMidiAccess({ nav }), and ports that only needsend()oronmidimessage. The site’s tests pass plain objects that record what was sent and fire fake events, so the whole flow runs in Node with no browser. - Permission states. Test denial deliberately. Block MIDI in the site settings and check that your error message is useful.
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.