Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read COM ports? navigator.serial.getPorts returns empty list

I have a small number of USB serial interfaces connected (a HF transceiver, CW keyer based on Arduino) and two bluetooth ports, that I never use and am not sure where do they come from (probably some application). In my SPA I need to read list of ports to be able to select which one to connect as which function.

However, when I call navigator.serial.getPorts() I always get an empty list. BTW, same for navigator.usb.getDevices() It runs on Chrome version 87.0.4280.141 (Official Build) (64-bit). Serial API is enabled.

How to solve this?

UPDATE: it is invoked from script in HTML file in local filesystem (not served over HTTP)

like image 684
Jindrich Vavruska Avatar asked Oct 18 '25 03:10

Jindrich Vavruska


2 Answers

You need to request the user's permission to read the Serial's ports by first calling navigator.serial.requestPort():

onclick = async () => {

  await navigator.serial.requestPort();
  console.log( await navigator.serial.getPorts() );

};

Live example

like image 182
Kaiido Avatar answered Oct 22 '25 06:10

Kaiido


You have to get permission to access any serial port by Serial.requestPort(). And the requestPort function can be called only with user activation, such as in click event callback.

After you get the permission of many serial ports, you can list the ports that you can access by Serial.getPorts().

getPorts function doesn't mean get the permission to serial ports, but lists the serials ports that you have had permission to access.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Serial

like image 40
yang piao Avatar answered Oct 22 '25 06:10

yang piao