Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome WebUSB API returns no device when using navigator.usb.getDevices()

I'm trying the new Chrome WebUSB API, but can't see any connected device.

Tried this for example, with different USB devices connected to my Windows 7 PC:

<html>
    <body>
        <button onclick="myFunction()">Click me</button>

        <script>
            function myFunction() {
                console.log('Clicked');
                navigator.usb.getDevices()
                  .then(devices => {
                    devices.map(device => {
                      console.log('Device:');
                      console.log(device.productName);
                      console.log(device.manufacturerName);
                    });
                  });
            }
        </script>
    </body>
</html>

But got no device.

What am I doing wrong? Should it work with any device?

like image 514
Guy Avatar asked Sep 08 '17 20:09

Guy


People also ask

What is USB API?

The USB interface of the WebUSB API provides attributes and methods for finding and connecting USB devices from a web page. Use navigator. usb to get access to the USB object. The USB interface inherits from EventTarget .


Video Answer


1 Answers

Until your page has requested permission to access a device navigator.usb.getDevices() will return an empty list. Inside your onclick handler call navigator.usb.requestDevice() instead with a filter selecting the vendor and product IDs of the devices you would like to support. See the example from the specification:

let button = document.getElementById('request-device');
button.addEventListener('click', async () => {
  let device;
  try {
    device = await navigator.usb.requestDevice({ filters: [{
        vendorId: 0xABCD,
        classCode: 0xFF, // vendor-specific
        protocolCode: 0x01
    }]});
  } catch () {
    // No device was selected.
  }

  if (device !== undefined) {
    // Add |device| to the UI.
  }
});
like image 131
Reilly Grant Avatar answered Oct 16 '22 20:10

Reilly Grant