我正在使用 Chrome Web Serial API,当我单击按钮并手动选择端口时,它工作正常。现在我想在打开页面时自动选择端口(COM1)。我不想单击按钮并选择端口。另外,当我重新加载页面时,我失去了与端口的连接。有谁知道我该怎么做?提前致谢!这是我的代码: "use strict"; class SerialScaleController { constructor() { this.encoder = new TextEncoder(); this.decoder = new TextDecoder(); } async init() { if ('serial' in navigator) { try { console.log(navigator) const port = await navigator.serial.requestPort(); await port.open({ baudRate: 9600 }); this.reader = port.readable.getReader(); let signals = await port.getSignals(); } catch (err) { console.error('There was an error opening the serial port:', err); } } else { console.error('Web serial doesn\'t seem to be enabled in your browser. Try enabling it by visiting:'); console.error('chrome://flags/#enable-experimental-web-platform-features'); console.error('opera://flags/#enable-experimental-web-platform-features'); console.error('edge://flags/#enable-experimental-web-platform-features'); } } async read() { try { const readerData = await this.reader.read(); console.log(readerData) return this.decoder.decode(readerData.value); } catch (err) { const errorMessage = `error reading data: ${err}`; console.error(errorMessage); return errorMessage; } } }
3 回答
肥皂起泡泡
TA贡献1829条经验 获得超6个赞
如果用户已经通过 requestPort() 批准了您一次,那么将来您可以使用 getPorts() 来获取您以前拥有的端口数组,如下所示。
// CanPrompt is 1 if being called from user button click etc
// Or 0 if calling from serial.onconnect or page load checking for device
var port = null;
if (CanPrompt) {
port = await navigator.serial.requestPort();
} else {
port = await navigator.serial.getPorts();
if ((port !== null) && (Array.isArray(port)) && (port.length > 0)) {
port = port[0];
} else return;
}
await port.open({ baudRate: 19200 });
添加回答
举报
0/150
提交
取消