Making a browser extension.
From the main window the scripts work as they should, but when I open them in the side panel the serial port selection window does not appear . As a consequence an error occurs: NotFoundError: Failed to execute ‘requestPort’ on ‘Serial’: No port selected by the user.
this is working code, it works fine in the browser window but when it runs in the side panel as an extension it doesn’t show the port selection popup window :
enter image description here – selection dialog (await navigator.serial.requestPort )
manifest.json
{
"name": "Side Panel Web Serial API",
"description": "SPWSAPI",
"version": "1.0",
"manifest_version": 3,
"permissions": ["sidePanel"],
"side_panel": {"default_path": "test.html"}
}
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Serial Api</title>
<script defer src="./serial.js"></script>
</head>
<body>
<button id="connectButton">Connect via Serial Port</button>
<div id="target"></div>
</body>
</html>
serial.js
async function connectSerial() {
const log = document.getElementById('target');
try {
const port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
const decoder = new TextDecoderStream();
port.readable.pipeTo(decoder.writable);
const inputStream = decoder.readable;
const reader = inputStream.getReader();
while (true) {
const { value, done } = await reader.read();
if (value) {
log.textContent += value + 'n';
}
if (done) {
console.log('[readLoop] DONE', done);
reader.releaseLock();
break;
}
}
} catch (error) {
log.innerHTML = error;
}
}
document.getElementById('connectButton').addEventListener('click', () => {
if (navigator.serial) {
connectSerial();
} else {
alert('Web Serial API not supported.');
}
});
Philip Khokhlov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.