9  Operating from the browser: Web Bluetooth console

With the Web Bluetooth API, you can connect to BLE devices from JavaScript in the browser. Use the console below on this page to operate a XIAO flashed with the sample firmware.

WarningRequirements
  • Works in Chrome / Edge (Windows, macOS, Linux, Android). Safari on iPhone / iPad and Firefox are not supported
  • Works only on HTTPS pages (or local localhost)
  • Connecting must be initiated by a user action such as a button click

9.1 Console

Disconnected
Version
—
Latest value
—
Seq. no. / samples
—
Mean / max
—
Measurement data (notified every second; mean = blue, max = red)
Log

TipTry it
  1. Press “Connect” and choose HANDSON_NRF52 from the list. Confirm that the XIAO’s LED changes to blinking blue
  2. Press “Device info” and confirm that 80 01 01 00 00 comes back
  3. Press “Start meas.”: the LED blinks red and the chart updates every second. Try shaking the XIAO
  4. While measuring, long-press the XIAO’s button to stop it. Get a feel for how BLE commands and the button are processed through the same state transition table
  5. Send 0300 (an undefined command) via the arbitrary hex field. What happens?

9.2 Key points of the code

device = await navigator.bluetooth.requestDevice({ filters: [{ services: [SERVICE] }] });
const server = await device.gatt.connect();
const svc = await server.getPrimaryService(SERVICE);
rx = await svc.getCharacteristic(RX);
tx = await svc.getCharacteristic(TX);
tx.addEventListener("characteristicvaluechanged", e => onNotify(e.target.value));
await tx.startNotifications();
  • requestDevice() makes the browser show a device selection dialog. Filtering by service UUID shows only devices that include that service in their advertising (this is where the firmware’s Bluefruit.Advertising.addService() takes effect)
  • The received value is a DataView. The true in getUint16(offset, true) specifies little-endian
  • In Web Bluetooth, running two GATT operations (read/write, starting Notify) at the same time causes an error (GATT operation already in progress). This console chains Promises to serialize them
NoteThe browser side is event-driven too

Receiving a Notify (characteristicvaluechanged), disconnecting (gattserverdisconnected), clicking a button — JavaScript in the browser has the same structure of receiving events and processing them.