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 start and stop characteristic notifications from a nearby Bluetooth Low Energy Device. You may want to try this demo with the BLE Peripheral Simulator App from the Google Play Store and check out the Notifications (Async Await) sample.
Live Output
JavaScript Snippet
varmyCharacteristic;functiononStartButtonClick(){letserviceUuid=document.querySelector('#service').value;if(serviceUuid.startsWith('0x')){serviceUuid=parseInt(serviceUuid);}letcharacteristicUuid=document.querySelector('#characteristic').value;if(characteristicUuid.startsWith('0x')){characteristicUuid=parseInt(characteristicUuid);}log('Requesting Bluetooth Device...');navigator.bluetooth.requestDevice({filters:[{services:[serviceUuid]}]}).then(device=>{log('Connecting to GATT Server...');returndevice.gatt.connect();}).then(server=>{log('Getting Service...');returnserver.getPrimaryService(serviceUuid);}).then(service=>{log('Getting Characteristic...');returnservice.getCharacteristic(characteristicUuid);}).then(characteristic=>{myCharacteristic=characteristic;returnmyCharacteristic.startNotifications().then(_=>{log('> Notifications started');myCharacteristic.addEventListener('characteristicvaluechanged',handleNotifications);});}).catch(error=>{log('Argh! '+error);});}functiononStopButtonClick(){if(myCharacteristic){myCharacteristic.stopNotifications().then(_=>{log('> Notifications stopped');myCharacteristic.removeEventListener('characteristicvaluechanged',handleNotifications);}).catch(error=>{log('Argh! '+error);});}}functionhandleNotifications(event){letvalue=event.target.value;leta=[];// Convert raw data bytes to hex values just for the sake of showing something.// In the "real" world, you'd use data.getUint8, data.getUint16 or even// TextDecoder to process raw data bytes.for(leti=0;i<value.byteLength;i++){a.push('0x'+('00'+value.getUint8(i).toString(16)).slice(-2));}log('> '+a.join(''));}