javascriptangularwebusb

WebUSB API - Unable to listen to device events


I am playing with WebUSB API for the first time. I use angular 9+ and right now I am just trying to connect to my USB mouse and listen to events when I move the mouse. I can successfully request the device and connect to the mouse however I am struggling to listen to events. Currently nothing happens after this.

Here is my code, what am I doing wrong? Thanks in advance.

BTW I am fully aware I can listen to mouse events with straight Javascript, this example is purely for testing out the WebUSB API.

HTML

<button (click)=test()>Connect</button> 

Component JS

declare global {
  interface Navigator {
      usb: {
          getDevices(): any;
          requestDevice({}):any;
          addEventListener({}):any;
          onconnect({}):any;
      }
  }
}
 async test() {
    console.log("Test");
    let device = await navigator.usb.requestDevice({filters:[]});
    await device.open();
    device.onconnect = (event) => {
      // Add event.device to the UI.
      console.log("EVENT",event);
    };
  }

Solution

  • 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.