Web Bluetooth API可在支持的浏览器中实现网页与BLE设备通信,需满足Chromium内核、安全上下文、蓝牙4.0+等条件,通过requestDevice选择设备并建立GATT连接,获取服务与特征值后可读写数据或监听通知,同时需处理错误与断开连接,适用于智能硬件控制等场景。

Web Bluetooth API 允许网页在用户授权的前提下,与附近的低功耗蓝牙(BLE)设备进行通信。这项功能主要支持现代浏览器如 Chrome 和 Edge,适用于开发无需原生应用即可控制 BLE 外设的网页应用,比如智能手环、传感器或物联网设备。
启用和使用 Web Bluetooth 的前提条件
要使用 Web Bluetooth API,需满足以下条件:
- 浏览器必须支持 Web Bluetooth(目前主要是 Chromium 内核浏览器,如 Chrome 56+)
- 运行环境必须是安全上下文(即 HTTPS 或 localhost)
- 用户设备需支持蓝牙 4.0 及以上,并已开启蓝牙功能
- 用户必须主动触发操作(例如点击按钮)来发起设备扫描
请求连接 BLE 设备
通过 navigator.bluetooth.requestDevice() 方法可以弹出系统级设备选择框,让用户从附近设备中选择目标设备。需要指定过滤条件,例如服务 UUID。
navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service'] }], // 按服务过滤
optionalServices: ['device_information'] // 需要访问其他服务时声明
})
.then(device => {
console.log('已选择设备:', device.name);
return device.gatt.connect(); // 建立 GATT 连接
})
.then(server => {
console.log('GATT 服务器已连接');
// 接下来可读写特征值
});
常见服务名称可使用标准 UUID 字符串或 16/128 位格式,例如 '0x180F' 表示电池服务。
读取和写入特征值
连接 GATT 服务器后,可通过 getPrimaryService() 和 getCharacteristic() 获取具体特征,进而进行数据交互。
- 读取数据:调用 characteristic.readValue() 获取当前值
- 写入数据:使用 characteristic.writeValue() 向设备发送指令
- 监听通知:调用 characteristic.startNotifications() 并监听 'characteristicvaluechanged' 事件
server.getPrimaryService('battery_service')
.then(service => service.getCharacteristic('battery_level'))
.then(characteristic => {
// 读取电量
return characteristic.readValue();
})
.then(value => {
const batteryLevel = value.getUint8(0);
console.log(`当前电量: ${batteryLevel}%`);
});
// 开启通知以实时接收更新
characteristic.addEventListener('characteristicvaluechanged', event => {
const value = event.target.value;
console.log('电量变化:', value.getUint8(0));
});
characteristic.startNotifications();
处理错误和断开连接
蓝牙操作容易受信号、权限或设备状态影响,建议对每个异步步骤添加 catch 处理。
.catch(error => {
console.error('蓝牙操作失败:', error);
});
当不再使用时,应主动调用 device.gatt.disconnect() 释放资源。也可监听设备断开事件:
device.addEventListener('gattserverdisconnected', () => {
console.log('设备已断开');
});
基本上就这些。只要设备兼容、权限允许,Web Bluetooth 能实现轻量高效的 BLE 通信,适合快速原型开发和简单控制场景。










