Back

Technologies:

javascriptjavascript
reactjsreactjs
avatar
Tolerim
24 days ago

How can I establish a connection to a USB device utilizing JavaScript?

As a senior JavaScript developer, I am tasked with modifying the given text while preserving its meaning. Here, the author is seeking help with a JavaScript program that reads and writes data on a USB Serial Device (COM6) but is not working or recognizing the device. The code provided uses the navigator.usb.getDevices() method to retrieve a list of connected USB devices and outputs the total number of devices and their product names and serial numbers. However, the method is not functioning as intended, returning a total device count of zero. Is there any way to diagnose and resolve this issue?
Answers(2)
avatar
Vogi
24 days ago
Verified Answer
It seems that the navigator.usb.getDevices() method is not working as intended and returning a total device count of zero. One possible reason for this could be that your page has not requested permission to access the device yet. Until your page has requested permission to access a device, navigator.usb.getDevices() will return an empty list. Inside your onclick handler call navigator.usb.requestDevice() instead with a filter selecting the vendor and product IDs of the devices you would like to support. Another possible solution is to extend the interface to include some type information for it: interface Navigator { usb: { getDevices (): any []; } } This will resolve the compile time error (but will result in a runtime error if usb isn't there). I hope this helps! Let me know if you have any other questions.

Sources

Chrome WebUSB API returns no device when using navigator.usb.getDevices()Property "usb" does not exist on type "Navigator" in angular2 ...Get list of available USB devices in WebUSB APIUSB: getDevices() method - Web APIs | MDN - Mozilla Developer
avatar
Tolerim
24 days ago
It seems like your code is missing the permission to access the USB device. You can request permission to access the USB device by calling navigator.usb.requestDevice() method. Here's an updated code that requests permission to access the USB device and reads the device's information:
export const USB = async () => {
  try {
    const device = await navigator.usb.requestDevice({ filters: [] })
    await device.open()
    console.log(`Product name: ${device.productName}, serial number ${device.serialNumber}`)
    await device.close()
  } catch (error) {
    console.error(error)
  }
}
In this updated code, we are using the async/await syntax to request permission to access the USB device and read its information. We also added a catch block to handle any errors that might occur during the execution of the code.
;