我正在尝试新的Chrome WebUSB API,但看不到任何连接的设备.
例如,尝试使用连接到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>
Run Code Online (Sandbox Code Playgroud)
但没有设备.
我究竟做错了什么?它应该适用于任何设备吗?
谢谢.
在您的页面请求访问设备的权限之前,navigator.usb.getDevices()将返回一个空列表.在onclick处理程序内部调用,navigator.usb.requestDevice()而是使用筛选器选择要支持的设备的供应商和产品ID.请参阅规范中的示例:
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.
}
});
Run Code Online (Sandbox Code Playgroud)