浏览器通过USB连接移动设备读取设备信息

发布时间 2023-12-23 22:05:59作者: 橘子味儿的猫

 

注意:一般情况下,浏览器只允许通过安全的传输协议(如HTTPS)或者本地的localhost和file协议来访问USB设备

这些限制是为了确保用户的隐私和安全。使用HTTPS协议可以加密数据传输,从而减少数据被窃取或篡改的风险。而本地的localhost和file协议则主要用于本地开发和测试环境,可以避免通过网络传输敏感数据。

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebUSB Example</title>
</head>
<body>
  <button id="request-device-button">Request USB Device</button>

  <script>
      const filters = [
        //{ vendorId:  } // 替换为你设备的vendorId和productId
      ];

    document.getElementById('request-device-button').addEventListener('click', () => {
      if ('usb' in navigator) {
        navigator.usb.requestDevice({ filters: filters })
          .then(device => {
            console.log('Device selected:', device);
            // 连接设备并进行通信
            // return device.open();
          })
          .then(() => {
            // 在此处进行数据传输等操作
          })
          .catch(error => {
            console.error('Error requesting device:', error);
          });
      } else {
        console.error('WebUSB API is not supported in this browser');
      }
    });
  </script>
</body>
</html>