我希望从使用WebUSB迁移到SerialAPI (很好地解释了这里)。
现行法典:
try {
let device = await navigator.usb.requestDevice({
filters: [{
usbVendorId: RECEIVER_VENDOR_ID
}]
})
this.connect(device)
} catch (error) {
console.log(DEVICE_NAME + ': Permission Denied')
}新法典:
try {
let device = await navigator.serial.requestPort({
filters: [{
usbVendorId: RECEIVER_VENDOR_ID
}]
})
this.connect(device)
} catch (error) {
console.log(DEVICE_NAME + ': Permission Denied')
}新代码似乎有效,但我认为这是因为浏览器已经通过旧代码请求了设备。
我试着重新启动Chrome,并清除所有浏览记录。甚至关闭了USB声明页面,并使用另一个应用程序(在此期间它返回DOMException: Unable to claim interface错误)来声明该设备,但Chrome似乎不想再问了。它只是愉快地将数据与前面的连接流在一起。
我希望使用SerialAPI是一种避免与其他进程争夺USB的方法,或者至少是输给它们。
更新
我忘记了:
Failed to execute 'requestPort' on 'Serial': "Must be handling a user gesture to show a permission request"这是否意味着用户需要使用按钮通过SerialUSB连接到设备?我认为,使用WebUSB,我能够使连接窗口自动弹出。
发布于 2020-12-08 23:30:07
对于这两个API,正如更新中所指出的,调用requestDevice()或requestPort()方法需要一个用户手势。不可能自动弹出此提示。(如果有错误,请让Chrome团队知道,这样我们就可以修复它了。)
通过WebUSB API和Web授予站点的权限目前分别被跟踪,因此通过其中一个访问设备的权限不会自动转换为另一个。
目前还没有一种以编程方式忘记设备权限的方法。这将需要已被放弃的navigator.permissions.revoke()方法。但是,您可以在访问站点时单击地址栏中的"lock“图标,或转到chrome://settings/content/usbDevice(用于USB设备)和chrome:// site /content/serialPorts(用于串行端口),从而手动撤销访问设备的权限。
发布于 2021-09-22 05:26:12
为了让Chrome“忘记”以前通过WebUSB API配对的navigator.usb.requestDevice设备:

发布于 2020-12-05 18:27:47
新代码不起作用。这似乎是因为Chrome已经通过旧代码与端口配对。“新代码”不可能奏效,因为正如Kalido的评论中所指出的,SerialAPI (由于其强大的功能)需要一个用户手势来连接。
我用于实际连接和获取数据的代码基本上是从OP中的上述链接中构建出来的:
navigator.serial.addEventListener('connect', e => {
// Add |e.target| to the UI or automatically connect.
console.log("connected");
});
navigator.serial.addEventListener('disconnect', e => {
// Remove |e.target| from the UI. If the device was open the disconnection can
// also be observed as a stream error.
console.log("disconnected");
});
console.log(navigator.serial);
document.addEventListener('DOMContentLoaded', async () => {
const connectButton = document.querySelector('#connect') as HTMLInputElement;
if (connectButton) {
connectButton.addEventListener('click', async () => {
try {
// Request Keiser Receiver from the user.
const port = await navigator.serial.requestPort({
filters: [{ usbVendorId: 0x2341, usbProductId: not_required }]
});
try {
// Open and begin reading.
await port.open({ baudRate: 115200 });
} catch (e) {
console.log(e);
}
while (port.readable) {
const reader = port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
break;
}
if (value) {
console.log(value);
}
}
} catch (error) {
// TODO: Handle non-fatal read error.
console.log(error);
}
}
} catch (e) {
console.log("Permission to access a device was denied implicitly or explicitly by the user.");
console.log(e);
console.log(port);
}
}
}设备特定的供应商和产品ID显然会在设备之间发生变化。在上面的例子中,我插入了一个Arduino供应商ID。
它没有回答如何让Chrome“忘记”的问题,但我不确定这是否与使用SerialAPI相关,因为这是必要的姿态。
希望有更多经验的人能够发布一个更有信息的答案。
https://stackoverflow.com/questions/65152371
复制相似问题