2017-09-08 278 views
2

我在嘗試新的Chrome WebUSB API,但無法看到任何連接的設備。Chrome WebUSB API在使用navigator.usb.getDevices()時返回任何設備

試過這個例如,與連接到我的Windows 7 PC的不同的USB設備:

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

,但沒有得到設備。

我在做什麼錯? 它是否適用於任何設備?

謝謝。

回答

5

直到您的頁面請求訪問設備的權限navigator.usb.getDevices()將返回一個空列表。在您的onclick處理程序中,請調用navigator.usb.requestDevice(),而不是使用篩選器來選擇您想要支持的設備的供應商和產品ID。見示例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. 
    } 
}); 
相關問題