The Web Bluetooth API brings hardware interaction to the browser, enabling web applications to communicate with Bluetooth Low Energy (BLE) devices. This opens up IoT use cases like connecting heart rate monitors, temperature sensors, and smart lights directly from web pages.
How Web Bluetooth Works
Web Bluetooth operates over the GATT (Generic Attribute Profile) protocol, which is standard for BLE communication. In this model, the BLE device acts as a peripheral that exposes services and characteristics, while the browser acts as the central that consumes them.
| Term | Description | Example |
|---|---|---|
| Service | Collection of characteristics | Battery Service (0x180F) |
| Characteristic | Data point with properties | Battery Level (0x2A19) |
| Descriptor | Metadata about a characteristic | Unit, description |
| UUID | Identifier for services/characteristics | 16-bit standard or 128-bit custom |
Web Bluetooth requires a secure context (HTTPS or localhost) and must be initiated by a user gesture. This security model prevents background scanning and unauthorized access.
Device Discovery and Connection
The first step is requesting a device from the browser:
async function connectDevice() {
try {
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service'] }],
optionalServices: ['environmental_sensing'],
});
const server = await device.gatt.connect();
console.log('Connected to:', device.name);
return server;
} catch (error) {
console.error('Connection failed:', error);
}
}
The filters parameter controls which devices appear in the browser chooser. Use name, namePrefix, or services to narrow results. optionalServices grants access to non-advertised services.
Reading and Writing Data
Once connected, access services and characteristics to exchange data:
async function readBatteryLevel(server) {
const service = await server.getPrimaryService('battery_service');
const characteristic = await service.getCharacteristic('battery_level');
const value = await characteristic.readValue();
return value.getUint8(0);
}
async function writeToCharacteristic(server, serviceUUID, charUUID, data) {
const service = await server.getPrimaryService(serviceUUID);
const characteristic = await service.getCharacteristic(charUUID);
await characteristic.writeValue(new TextEncoder().encode(data));
}
For real-time data, subscribe to notifications:
const characteristic = await service.getCharacteristic('heart_rate_measurement');
await characteristic.startNotifications();
characteristic.addEventListener('characteristicvaluechanged', (event) => {
const value = event.target.value;
// Parse heart rate data from ArrayBuffer
});
Reconnection and Connection Management
Handle disconnections gracefully and implement reconnection:
const device = await navigator.bluetooth.requestDevice({ filters: [...] });
device.addEventListener('gattserverdisconnected', () => {
console.log('Device disconnected, attempting reconnect...');
setTimeout(async () => {
if (device.gatt.connected) return;
await device.gatt.connect();
}, 1000);
});
await device.gatt.connect();
Use device.watchAdvertisements() to detect devices in proximity, enabling location-aware features.
Security Considerations
Web Bluetooth enforces security at multiple levels. The secure context requirement (HTTPS) ensures encrypted transport. User gesture requirements prevent unauthorized scanning. Pairing may involve authentication with passkey entry or numeric comparison, depending on device capabilities.
Devices the user has previously allowed are accessible via navigator.bluetooth.getDevices(), but the browser never exposes devices without explicit user consent.
Limitations and Alternatives
Web Bluetooth has important limitations: it supports BLE only (not classic Bluetooth), has no background scanning on mobile browsers, and iOS Safari support remains experimental. Effective range is about 10-30 meters with a ~20-byte payload limit per packet.
For scenarios beyond Web Bluetooth’s capabilities, consider Web Serial (for serial port communication), Web USB, or a native companion app bridged via WebSocket.
The Web Bluetooth API enables a new class of web applications that interact with the physical world. Start with simple patterns like reading sensor data or receiving notifications, then progress to bidirectional communication and bonding for more advanced use cases.
