WebUSB API - Unable to listen to device events
This is as far as you will get with a USB mouse because the browser will not let a site claim the USB interface which is used for input events.
The code you've written is incorrect because it is listening for connect events on the USBDevice interface. These events are fired on the USB interface (specifically, navigator.usb) and so you want to write code like this to detect connect and disconnect:
navigator.usb.addEventListener('connect', (event) => {
console.log("Device connected", event.device);
});
navigator.usb.addEventListener('disconnect', (event) => {
console.log("Device disconnected", event.device);
});
Note that these events are only fired for devices the site already has access to so you always have to start by requesting device access with navigator.usb.requestDevice(). The events (and navigator.usb.getDevices()) are useful for re-establishing connections to a device in a new session.
浙公网安备 33010602011771号