WebHID API
注意:此功能在 Web Workers 中可用,但 共享 Web Workers 除外。
人机接口设备 (HID) 是一种从人获取输入或向人提供输出的设备类型。它也指 HID 协议,一个用于主机和设备之间进行双向通信的标准,旨在简化安装过程。HID 协议最初是为 USB 设备开发的,但后来已被实现到许多其他协议中,包括蓝牙。
接口
HID-
提供连接 HID 设备、列出已连接 HID 设备的方法以及连接 HID 设备的事件处理程序。
HIDDevice-
表示一个 HID 设备。一个物理设备可能由多个
HIDDevice对象表示。 HIDInputReportEvent-
当从任何关联的 HID 设备接收到输入报告时,会传递给
HIDDevice的inputreport事件。 HIDConnectionEvent-
当设备连接或断开连接时,会传递给
HID的connect和disconnect事件。
示例
您可以使用 requestDevice() 方法连接到设备。在这种情况下,我们将从所有可用设备中进行选择。
js
const device = await navigator.hid.requestDevice({ filters: [] });
// A popup titled `... wants to connect to a HID Device` with `Cancel` and `Connect` buttons will show up with a device list to select from.
// Select one and click on `Connect` button. Then the device will be an array with the selected device in it.
我们可以检索网站先前已被授予访问权限的所有设备,并将设备名称记录到控制台。
js
let devices = await navigator.hid.getDevices();
devices.forEach((device) => {
console.log(`HID: ${device.productName}`);
});
我们可以为任何 HID 设备的断开连接注册事件监听器。
js
navigator.hid.addEventListener("disconnect", (event) => {
console.log(`HID disconnected: ${event.device.productName}`);
console.dir(event);
});
// For example, when my connected keyboard gets disconnected, the log in the console will show:
// HID disconnected: USB Keyboard
// {
// bubbles: false
// cancelBubble: false
// cancelable: false
// composed: false
// currentTarget: HID {onconnect: null, ondisconnect: null}
// defaultPrevented: false
// device: HIDDevice {oninputreport: null, opened: false, vendorId: 6700, productId: 11555, productName: "USB Keyboard", …}
// eventPhase: 0
// isTrusted: true
// path: []
// returnValue: true
// srcElement: HID {onconnect: null, ondisconnect: null}
// target: HID {onconnect: null, ondisconnect: null}
// timeStamp: 18176.600000023842
// type: "disconnect"
// }
// The event above is an instance of the HIDConnectionEvent interface.
规范
| 规范 |
|---|
| WebHID API # dom-hid |
浏览器兼容性
加载中…