skip to Main Content

I’m using WebSerial and I have a problem after the first authorization.

This is code for the first time (with popup user authorization):

port = await navigator.serial.requestPort();            
await port.open({ baudRate: 9600 });

all works correctly.

But next time, I using this code:

await navigator.serial.getPorts().then((ports) => {
    if(ports.length>0){
        port = ports[0]; 
        port.open({ baudRate: 9600 });              
    }
}); 

And return this error: "Uncaught (in promise) DOMException: Failed to execute ‘open’ on ‘SerialPort’: Failed to open serial port."

Why?

2

Answers


  1. Chosen as BEST ANSWER

    Thank you GifftyCode,

    this is the scenario: inside the web page the user asks to connect to the COM, he selects it using the popup (requestPort()). Next time the user requests to connect to the serial port and should not see the popup, but reconnect by selecting port[0] from getPorts(). Everything is not very clear in Chrome (v.126.0.6478.128) this error is reported, not when you using Firefox Mozilla (v.128.0).

    This is the object returned the first time (with requestPort() ):

    SerialPort {onconnect: null, ondisconnect: null, readable: ReadableStream, writable: WritableStream}

    This is the object returned the second time (with getPorts() ):

    SerialPort {onconnect: null, ondisconnect: null, readable: null, writable: null}

    Why readable and writable is different?


  2. Before reopening a port, do you close properly before reopening again and when reusing an authorized port, do you properly open it?

    Sample Code:

        async function closePort(port) {
        if (port.readable || port.writable) {
            await port.close();
        }
    }
    
    async function openPort() {
        try {
            let ports = await navigator.serial.getPorts();
            if (ports.length > 0) {
                let port = ports[0];
                await closePort(port); // Ensure the port is closed before reopening
                await port.open({ baudRate: 9600 });
            } else {
                // Request user authorization if no ports are available
                port = await navigator.serial.requestPort();            
                await port.open({ baudRate: 9600 });
            }
        } catch (error) {
            console.error("Failed to open the port:", error);
        }
    }
    
    // Use the function to open the port
    openPort();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search