首页 > 解决方案 > 覆盖 navigator.bluetooth.requestDevice() 的默认行为

问题描述

当我调用 navigator.bluetooth.requestDevice({acceptAllDevices: true}) 时,会弹出一个带有我周围设备的 chrome 窗口。我只能在这里选择 1 个设备。有没有办法选择多个设备或不弹出此窗口;我可以实现我自己的基于 Web 的窗口来显示我周围的 BLE 设备吗?

navigator.bluetooth.requestDevice({acceptAllDevices: true})
         .then(device => {
              console.log(device);
         });

在此处输入图像描述

标签: google-chromebluetoothweb-bluetooth

解决方案


新的navigator.bluetooth.getDevicesAPI(在 Chrome 85 及更高版本中)实际上允许您避免此提示,如果您以前用于requestDevice配对设备。

它上面的 chromestatus 页面在这里:https ://www.chromestatus.com/feature/4797798639730688

它包含指向开发人员指南的链接。

最简单的hackiest用法是:

navigator.bluetooth.getDevices().then(function(devices) {
  if (devices.length==0) put_up_button_for_requestDevice();
  else return devices[0].gatt.connect();
}).then(finish_connecting_as_normal)

推荐阅读