0

I'm using the Chrome Web Serial API and it works fine when I click on button and select the port manually. Now I want to select automatically the port (COM1) when open a page. 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>

3 Answers 3

2

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.

// 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

Sign up to request clarification or add additional context in comments.

Comments

0

I believe one requirement of web serial is to require a user interaction for security in addition to being delivered on a site that has TLS.

Comments

-1

Have you thought about using a cookie as a 'persistent' setting? IE https://www.w3schools.com/js/js_cookies.asp

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.