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
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?
Before reopening a port, do you close properly before reopening again and when reusing an authorized port, do you properly open it?