Bluetooth over the Web

Krishna Ojha
5 min readMay 5, 2020

--

Bluetooth Technology has been widely spreading every single day due to its availability in most of the electronic devices that are dominant nowadays. When speaking of Bluetooth, what come first to your mind? Wireless headphones, car audio system, your fitness band or may be wireless data transfer between devices, but what if I told you that you could communicate with websites via Bluetooth devices and that too in a secure manner. Sounds cool? Then let’s dive a bit deeper.

Connecting to Bluetooth devices have only been a feature of native apps until now but with the Web Bluetooth API aims to bring this to web browsers as well. This tech is under-development currently but the Chrome team has announced that a subset of the Web Bluetooth API is now enabled in Chrome on Android, Chrome OS, and Mac. This lets you to request and connect to nearby Bluetooth devices, read/write Bluetooth characteristics, receive GATT Notifications, and know when a Bluetooth device gets disconnected. It even gives you the ability to read and write to Bluetooth descriptors. You could check its status on other browsers on the Implementation Status Page.

Since we are talking about Bluetooth, our basic concepts of Bluetooth Low Energy (BLE) and the working of Generic Attribute Profile (GATT) should be clear, so let’s have a quick look of what these terms mean.

Bluetooth Low Energy

Bluetooth Low Energy

BLE is a wireless personal area network technology designed and marketed by the Bluetooth Special Interest Group (Bluetooth SIG) aimed at novel applications in the healthcare, fitness, beacons, security, and home entertainment industries. Compared to Classic Bluetooth, Bluetooth Low Energy is intended to provide considerably reduced power consumption and cost while maintaining a similar communication range.

Generic Attribute Profile (GATT)

It basically defines the way that two Bluetooth Low Energy devices transfer data back and forth using concepts called Services and Characteristics. It makes use of a generic data protocol called the Attribute Protocol (ATT), which is used to store Services, Characteristics and related data in a simple lookup table using 16-bit IDs for each entry in the table. You can check the various GATT specifications here.

Now that we know a bit about Bluetooth, its time we jump into integrating it with the web!

Security First

Keeping security in mind the Chrome Team has designed the Bluetooth API in a way which makes it available to only secure contexts like the HTTPS. For development purposes interaction with Web Bluetooth is possible through localhost but for deployment, a server with an HTTPS setup is a must. For better security, discovering Bluetooth devices with must be triggered by a user gesture such as a touch or a mouse click.

The Coding Part

The Web Bluetooth API relies highly on JavaScript Promises introduced in the ES6 in 2015. The Promise object basically represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

There is a lot that you could do with the Web Bluetooth API, but for this Article I’d be covering

1) How to request Bluetooth Devices

2) How to connect to a Bluetooth Device

3) A simple example illustrating the use of the Web Bluetooth API to retrieve basic device information from a nearby Bluetooth Low Energy Device.

For even more information do check this amazing article by François Beaufort which has been an inspiration for this blog. So for now, let’s get going…

Requesting Bluetooth Device

For requesting a nearby device we use the navigator.bluetooth.requestDevice function of the API. This function takes a mandatory Object that defines filters which are used to return only those devices that match some advertised Bluetooth GATT services and/or the device name.

The following code snippet could be used for scanning all nearby Bluetooth devices and return the battery_services. You could check other available Bluetooth GATT Services here.

navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: ['battery_service']
})
.then(device => { /* Operation you desire to perform */ })
.catch(error => { console.log(error); });

Connecting to Bluetooth Device

Once you have a Bluetooth Low Energy device returned by the above method, you could now proceed with connecting your browser with it using the function. The following code snippet demonstrated it usage.

navigator.bluetooth.requestDevice({ 
filters: [{ services: ['battery_service'] }]
})
.then(device => {
console.log(device.name);
return device.gatt.connect();
})
.then(server => { /* Operation you desire to perform */ })
.catch(error => { console.log(error); })

Retrieving basic device information

Here I’ll be covering a sample code letting you retrieve basic device information from a nearby Bluetooth Low Energy Device. For more such sample codes refer this page.

HTML Snippet

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<title>Web Bluetooth</title>
</head>

<body>
<button onclick="onButtonClick()">Scan Devices</button>
<script src="webBluetooth.js"></script>
</body>
</html>

JavaScript Snippet

function onButtonClick() {
let filters = [];

let filterService = document.querySelector('#service').value;
if (filterService.startsWith('0x')) {
filterService = parseInt(filterService);
}
if (filterService) {
filters.push({services: [filterService]});
}

let filterName = document.querySelector('#name').value;
if (filterName) {
filters.push({name: filterName});
}

let filterNamePrefix = document.querySelector('#namePrefix').value;
if (filterNamePrefix) {
filters.push({namePrefix: filterNamePrefix});
}

let options = {};
if (document.querySelector('#allDevices').checked) {
options.acceptAllDevices = true;
} else {
options.filters = filters;
}

log('Requesting Bluetooth Device...');
log('with ' + JSON.stringify(options));
navigator.bluetooth.requestDevice(options)
.then(device => {
log('> Name: ' + device.name);
log('> Id: ' + device.id);
log('> Connected: ' + device.gatt.connected);
})
.catch(error => {
log('Argh! ' + error);
});
}

This indeed is a cool technology with endless possibilities in the Health, Entertainment and IoT segment. Hope you now have a better understanding of Bluetooth and how you could use the Web Bluetooth API to let your next website be able to connect with nearby BLE devices.

--

--

Krishna Ojha

Web Development is love, Artificial Intelligence my craze and Hardware is my passion. A complete tech enthusiast!