简体   繁体   English

Web Serial API - 自动读取

[英]Web Serial API - Automatically read

I'm using the Chrome Web Serial API and it works fine when I click on button and select the port manually.我正在使用 Chrome Web Serial API,当我单击按钮并手动选择端口时它工作正常。 Now I want to select automatically the port (COM1) when open a page.现在我想在打开页面时自动选择端口(COM1)。 I don't want click the button and select the port.我不想单击按钮并选择端口。 Also, when I reload the page I lost connection to the port.此外,当我重新加载页面时,我失去了与端口的连接。 Does anyone know how could I do that?有谁知道我怎么能这样做? Thanks in advance!提前致谢!

This is my code:这是我的代码:

 "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; } } } const serialScaleController = new SerialScaleController(); const connect = document.getElementById('connect-to-serial'); const getSerialMessages = document.getElementById('get-serial-messages'); connect.addEventListener('pointerdown', () => { serialScaleController.init(); }); getSerialMessages.addEventListener('pointerdown', async () => { getSerialMessage(); }); async function getSerialMessage() { document.querySelector("#serial-messages-container .message").innerText += await serialScaleController.read() }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Web Serial</title> </head> <body> <div class="serial-scale-div"> <button class="btn" id="connect-to-serial">Connect with Serial Device</button> </div> <button id="get-serial-messages">Get serial messages</button> <div id="serial-messages-container"> <div class="message"></div> </div> </body> </html>

Have you thought about using a cookie as a 'persistent' setting?您是否考虑过使用 cookie 作为“持久”设置? IE https://www.w3schools.com/js/js_cookies.asp IE https://www.w3schools.com/js/js_cookies.asp

Good luck!祝你好运!

If the user has approved you once via requestPort(), then in future you can use getPorts() to get an array of ports you've previously had, something like this.如果用户通过 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 });

More background info can be found in a closed git issue https://github.com/WICG/serial/issues/131更多背景信息可以在封闭的 git 问题https://github.com/WICG/serial/issues/131 中找到

我相信 web 序列的一个要求是除了在具有 TLS 的站点上交付之外,还需要用户交互以确保安全

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM