Web Bluetooth / Get Devices (Async Await) Sample

Available in Chrome 87+ | View on GitHub | Browse Samples

The Web Bluetooth API lets websites discover and communicate with devices over the Bluetooth 4 wireless standard using the Generic Attribute Profile (GATT). It is currently partially implemented in Android M, Chrome OS, Mac, and Windows 10.

This sample illustrates the use of the Web Bluetooth API to get a list of Bluetooth devices that the website has been granted permission to use by the user. You may want to check out the Get Devices sample.

Live Output


JavaScript Snippet

async function onGetBluetoothDevicesButtonClick() {
  try {
    log('Getting existing permitted Bluetooth devices...');
    const devices = await navigator.bluetooth.getDevices();

    log('> Got ' + devices.length + ' Bluetooth devices.');
    for (const device of devices) {
      log('  > ' + device.name + ' (' + device.id + ')');
    }
  }
  catch(error) {
    log('Argh! ' + error);
  }
}

async function onRequestBluetoothDeviceButtonClick() {
  try {
    log('Requesting any Bluetooth device...');
    const device = await navigator.bluetooth.requestDevice({
   // filters: [...] <- Prefer filters to save energy & show relevant devices.
      acceptAllDevices: true
    });

    log('> Requested ' + device.name + ' (' + device.id + ')');
  }
  catch(error) {
    log('Argh! ' + error);
  }
}