Access serial port in web worker

Viewed 184

I want to access the serial port navigator.serial.requestPort() in web worker, but I get this error:

Uncaught (in promise) TypeError: navigator.serial.requestPort is not a function

How can I fix this ?

1 Answers

You can't call requestPort from a worker, you'll need to call requestPort in the main application code then tell the worker to open the port.

Main code:

await navigator.serial.requestPort();

workerRef.current.postMessage('connect');

Worker Code:

onmessage = async (evt) => {
    if (evt.data === 'connect') {
        [port] = await navigator.serial.getPorts();

        const info = await port.open({ baudRate: 19200 });
    }
}

Example on stackblitz

Related