5

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Guy
  • 1,547
  • 1
  • 18
  • 29

1 Answers1

6

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.
  }
});
Reilly Grant
  • 5,590
  • 1
  • 13
  • 23
  • I tried that, but it threw an exception. Is this answer outdated? the spec has this code: document.addEventListener('DOMContentLoaded', async () => { let devices = await navigator.usb.getDevices(); devices.forEach(device => { // Add |device| to the UI. }); }); I don't get a permission request, just an empty list no matter what I try. – Chris Love Oct 03 '18 at 22:16