简体   繁体   English

使用 navigator.usb.getDevices() 时,Chrome WebUSB API 不返回任何设备

[英]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.我正在尝试新的 Chrome WebUSB API,但看不到任何连接的设备。

Tried this for example, with different USB devices connected to my Windows 7 PC:例如,尝试将不同的 USB 设备连接到我的 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?它应该适用于任何设备吗?

Until your page has requested permission to access a device navigator.usb.getDevices() will return an empty list. 在页面请求访问设备的权限之前, navigator.usb.getDevices()将返回一个空列表。 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. 在您的onclick处理程序中,调用navigator.usb.requestDevice()而不是使用过滤器选择要支持的设备的供应商和产品ID。 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.
  }
});

device = await navigator.usb.requestDevice({ filters: [{ vendorId: 0xABCD, classCode: 0xFF, // vendor-specific protocolCode: 0x01 }]}); device = await navigator.usb.requestDevice({ filters: [{ vendorId: 0xABCD, classCode: 0xFF, // 供应商特定的协议代码: 0x01 }]});

navigator comes from?导航器从何而来?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM