1

I need your help.

Is there a way to take control of a serial port, previously authorized, without using the popup window? (without port = await navigator.serial.requestPort();)

Thank you and sorry for my english, italian speaking here.

Fra
  • 11
  • 2
  • P.S. I'm trying to print receipts on an old EPSON TM-T81 from a webpage using javascript. – Fra Nov 10 '21 at 21:14
  • I found: // Get all serial ports the user has previously granted the website access to. const ports = await navigator.serial.getPorts(); but I'm not able to use it... https://web.dev/serial/ – Fra Nov 10 '21 at 21:17
  • Please provide enough code so others can better understand or reproduce the problem. – Community Nov 17 '21 at 05:29
  • this seems to work: `const ports = await navigator.serial.getPorts(); if(ports.length==0){ port = await navigator.serial.requestPort(); }else{ port=ports[0]; } await port.open({ baudRate: 9600 });` – Fra Nov 18 '21 at 21:13

2 Answers2

1

I believe JS code below should work fine for you:

// Get all serial ports the user has previously granted the website access to.
const ports = await navigator.serial.getPorts();

Source: https://web.dev/serial/#open-port

François Beaufort
  • 4,843
  • 3
  • 29
  • 38
  • 1
    this will only work, for previously authorised ports – Xsmael Feb 14 '22 at 20:25
  • Indeed. Web Serial doesn't allow you get access to ports without user consent. – François Beaufort Feb 15 '22 at 08:22
  • Yeah, security concerns. But there are cases where you really need that, for example my case: make desktop application using NW.JS, so technically its a desktop application, but it still uses chrome under the hood, and for a good user experience you want to have direct access to serial ports like any other program. In that case you really need to bypass permissions – Xsmael Feb 16 '22 at 16:01
  • In that case, I'd look at filing feature requests against NW.JS or Electron to be able to do that. The web platform won't provide this for sure. – François Beaufort Feb 17 '22 at 07:20
0

Run this code on first mouse or keyboard event, it will pop port permission on first run and should fetch port automatically on next runs.

// specify device details
let usbVendorId = 0x0403, // Arduino
    usbProductId = 0x6001; // Nano

// get serial ports
navigator.serial
.getPorts()
.then(
    ports => {

        // no ports available, prompt user permission
        if(!ports.length) 
            return navigator.serial
            .requestPort({
                filters: [{usbVendorId, usbProductId}]
            });
        // port is available
        else 
            return Promise
            .resolve(ports[0]);

    }
)
.then(
    port => {

        port
        .open({
            baudRate: 9600
        })
        .then(
            () => {

                const reader = port.readable.getReader();

                // ...

            }
        );

    }
);
nicopowa
  • 459
  • 3
  • 11