The WebUSB API provides a way to expose non-standard Universal Serial Bus (USB) compatible devices services to the web, to make USB safer and easier to use.
USB is the de-facto standard for wired peripherals. The USB devices that you connect to your computer are typically grouped into a number of device classes—such as keyboards, mice, video devices, and so on. These are supported using the operating system's class driver. Many of these are also web accessible via the WebHID API
.
In addition to these standardized devices, there are a large number of devices that don't fit into any class. These need custom drivers, and are inaccessible from the web due to the native code required to take advantage of them. Installing one of these devices often involves searching on a manufacturer's website for drivers and, should you wish to use the device on another computer, repeating the process again.
WebUSB provides a way for these non-standardized USB device services to be exposed to the web. This means that hardware manufacturers will be able to provide a way for their device to be accessed from the web, without having to provide their own API.
When connecting a new WebUSB-compatible device, the browser displays a notification providing a link to the manufacturer's website. On arriving at the site the browser prompts for permission to connect to the device, then the device is ready for use. No drivers need be downloaded and installed.
The following example demonstrates how to access a connected Arduino device using USB.requestDevice()
, which has a vendorId of 0x2341
.
navigator.usb
.requestDevice({ filters: [{ vendorId: 0x2341 }] })
.then((device) => {
console.log(device.productName);
console.log(device.manufacturerName);
})
.catch((error) => {
console.error(error);
});
You can find all connected devices with USB.getDevices()
. In the following example, with the Arduino device connected, product and manufacturer name are printed to the console.
navigator.usb.getDevices().then((devices) => {
devices.forEach((device) => {
console.log(device.productName);
console.log(device.manufacturerName);
});
});