Web蓝牙,获取配对设备列表

时间:2020-03-09 16:09:01

标签: javascript web bluetooth web-bluetooth

我在项目中使用Web蓝牙,使用此代码连接到设备

async function requestDevice() {
    bluetoothDevice = await navigator.bluetooth.requestDevice({
        // filters: [ { name: 'Device test' } ],
        acceptAllDevices: true,
        optionalServices: [
            'battery_service',
            '03b80e5a-ede8-4b33-a751-6ce34ec4c700'
        ]
    });

    bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);       
} 

始终连接,我会调用对话框,然后在其中选择所需的设备。我可以以编程方式获取已连接设备的列表吗?为了不每次都调用对话框?

1 个答案:

答案 0 :(得分:4)

目前尚无法获取Chrome中的蓝牙设备列表。但是,我正在为蓝牙实现getDevices()方法。请遵循Chrome Platform Status

中的状态

6/22/20编辑:

我最近实现了一个新的权限后端以及两个API,这些API将允许使用先前允许的蓝牙设备。

新权限后端在chrome:// flags /#enable-web-bluetooth-new-permissions-backend后面实现。新的后端将保留通过requestDevice()授予的设备权限,直到在“网站设置”或“页面信息”对话框中重置权限为止。

对于Chrome 85.0.4165.0或更高版本,getDevices()watchAdvertisements()在chrome:// flags /#enable-experimental-web-platform-features标志之后实现。这些API的建议用法是使用getDevices()检索允许的BluetoothDevices数组,然后在这些设备上调用watchAdvertisements()开始扫描。当从设备检测到广告包时,advertisementreceived事件将在与其对应的设备上触发。此时,蓝牙设备已在范围内并且可以连接。

请尝试使用此新功能,并使用Blink>蓝牙组件在https://crbug.com上提交所有错误。