概述Web Bluetooth 允许网页通过蓝牙低功耗(BLE)与设备通信。需用户手势授权与 HTTPS,适用于传感器读取、控制器交互等场景。示例const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service'] }]
})
const server = await device.gatt.connect()
const service = await server.getPrimaryService('battery_service')
const char = await service.getCharacteristic('battery_level')
const value = await char.readValue()
console.log(value.getUint8(0))
// 订阅通知
await char.startNotifications()
char.addEventListener('characteristicvaluechanged', e => {
const v = e.target.value.getUint8(0)
})
工程建议设备过滤:使用明确 `filters` 限定设备范围;减少误选与权限问题。连接管理:处理断开与重连;设置超时与错误回退。安全与隐私:限制来源与数据处理;避免对敏感设备的无约束访问。参考与验证MDN Web Bluetooth 文档:https://developer.mozilla.org/docs/Web/API/Web_Bluetooth_APIChrome 平台文档:https://developer.chrome.com/docs/web-platform/bluetooth/Web Bluetooth CG 规范:https://webbluetoothcg.github.io/web-bluetooth/

发表评论 取消回复