Bluetooth

The Web Bluetooth API is a low-level API allowing Web applications to access the services exposed by nearby Bluetooth-enabled devices.

API glimpse

navigator.bluetooth.requestDevice(serviceFilters)
Scans for the device in range supporting the requested services. Returns a Promise.
device.gatt.connect()
Returns a Promise resolved with the server object providing access to the services available on the device.
server.getPrimaryService(name)
Returns a Promise resolved with the particular Bluetooth service on the device.
service.getCharacteristic(name)
Returns a Promise resolved with the GATT characteristic object.
characteristic.readValue()
Returns a Promise resolved with a raw value from the GATT characteristic.
characteristic.writeValue(value)
Writes a new value for the GATT characteristic.

Live Demo

Based on code snippets from Google Developers.

  • function readBatteryLevel() {
      var $target = document.getElementById('target');
      
      if (!('bluetooth' in navigator)) {
        $target.innerText = 'Bluetooth API not supported.';
        return;
      }
      
      navigator.bluetooth.requestDevice({
          filters: [{
            services: ['battery_service']
          }]
        })
        .then(function (device) {
          return device.gatt.connect();
        })
        .then(function (server) {
          return server.getPrimaryService('battery_service');
        })
        .then(function (service) {
          return service.getCharacteristic('battery_level');
        })
        .then(function (characteristic) {
          return characteristic.readValue();
        })
        .then(function (value) {
          $target.innerHTML = 'Battery percentage is <b>' + value.getUint8(0) + '</b>.';
        })
        .catch(function (error) {
          $target.innerText = error;
        });
    }
  • <p>
      <button class="btn btn-lg btn-default" onclick="readBatteryLevel()">Read Bluetooth device's battery level</button>
    </p>
    
    <p id="target"></p>
    
    <p><small>Based on code snippets from <a href="https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web" target="_blank">Google Developers</a>.</small></p>

Resources