WebHID API
The WebHID API allows websites to access alternative Human Interface Devices (HID) that are not fully supported by standard browser drivers. This includes devices like game controllers (that don't fit the Gamepad API), medical devices, industrial controls, and custom hardware.
1. The Concept
Standard HIDs like keyboards and mice are handled by the operating system and browser automatically. However, many devices use the HID protocol but don't have standard drivers. WebHID gives JavaScript direct access to these devices' input and output reports.
2. The Connection Flow
- Request Device: Ask the user to select a HID device.
- Open: Open a connection to the device.
- Listen: Receive "Input Reports" (data from device).
- Send: Send "Output Reports" (data to device).
3. Requesting a Device
Like WebUSB and Web Bluetooth, this requires a user gesture.
const button = document.getElementById('connect-hid');
button.addEventListener('click', async () => {
try {
// Filter by Vendor ID (VID) and Product ID (PID)
const devices = await navigator.hid.requestDevice({
filters: [{ vendorId: 0x1234, productId: 0x5678 }]
});
if (devices.length > 0) {
const device = devices[0];
console.log(`HID: ${device.productName}`);
await connectDevice(device);
}
} catch (error) {
console.error('HID Error:', error);
}
});
4. Connecting and Communicating
Once you have the device object, you open it and set up event listeners.
async function connectDevice(device) {
await device.open();
console.log('Device opened!');
// Listen for Input Reports (Data coming from the device)
device.addEventListener('inputreport', (event) => {
const { data, device, reportId } = event;
// data is a DataView
// Example: Read the first byte
const value = data.getUint8(0);
console.log(`Report ID: ${reportId}, Value: ${value}`);
});
// Send an Output Report (Data going to the device)
// reportId (0 if not used), data (TypedArray or DataView)
const data = new Uint8Array([0x01, 0x02]);
await device.sendReport(0, data);
}
5. Security and Privacy
- HTTPS: Only works on secure contexts.
- User Gesture:
requestDevicemust be triggered by a user interaction. - Permission: The user must explicitly select the device from a browser-provided dialog.
6. Events
You can track when devices are connected or disconnected (if the user has previously granted permission).
navigator.hid.addEventListener('connect', ({ device }) => {
console.log(`HID connected: ${device.productName}`);
});
navigator.hid.addEventListener('disconnect', ({ device }) => {
console.log(`HID disconnected: ${device.productName}`);
});
programming/javascript/vanilla/javascript programming/javascript/vanilla/promises-async-await programming/javascript/vanilla/typed-arrays