您好,我正在尝试从用 reactjs 编写的电子应用程序中访问 U 盘。
由于电子是谷歌铬,我想我可以使用USB Web-API:https://developer.mozilla.org/en-US/docs/Web/API/USB
所以我创建了一个这样的组件:
import React from 'react';
const UsbAccessButton = () => (
<button
className="usb-access-button"
onClick={() => {
navigator.usb
.requestDevice({ filters: [{ vendorId: 0x0951 }] })
.then(device => {
console.log(device.productName);
console.log(device.manufacturerName);
})
.catch(error => {
console.log(error);
});
}}
>
Get USB Access
</button>
);
export default UsbAccessButton;
供应商 ID 是我的特定 U 盘的正确版本。但是当我单击该按钮时,我收到如下错误:
DOMException: No device selected. usb-access-button.component.jsx:14
但我想列出可用的设备,以便用户可以在两者之间进行选择。所以也许我不明白文档的某些部分或导致这里出现问题的原因?
更新: 当我在默认的chrome浏览器中运行此应用程序时,我会看到在USB设备之间进行选择的对话框。所以看起来这个误差更多地与电子本身有关。
目前(2020 年 1 月(不可能在 Electron 中为 WebUSB 设置设备选择器 - 请参阅此处的问题:https://github.com/electron/electron/issues/14545
目前建议的解决方案是使用thegecko/webusb polyfill,它使用node-usb库。