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 |
瀏覽器相容性
載入中…