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 write to the
descriptor "Characteristic User Description" on 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 Write Descriptor (Async Await) sample.
Live Output
JavaScript Snippet
varmyDescriptor;functiononReadButtonClick(){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 any Bluetooth Device...');navigator.bluetooth.requestDevice({// filters: [...] <- Prefer filters to save energy & show relevant devices.acceptAllDevices:true,optionalServices:[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=>{log('Getting Descriptor...');returncharacteristic.getDescriptor('gatt.characteristic_user_description');}).then(descriptor=>{document.querySelector('#writeButton').disabled=!descriptor.characteristic.properties.write;myDescriptor=descriptor;log('Reading Descriptor...');returndescriptor.readValue();}).then(value=>{letdecoder=newTextDecoder('utf-8');log('> Characteristic User Description: '+decoder.decode(value));}).catch(error=>{document.querySelector('#writeButton').disabled=true;log('Argh! '+error);});}functiononWriteButtonClick(){if(!myDescriptor){return;}letencoder=newTextEncoder('utf-8');letvalue=document.querySelector('#description').value;log('Setting Characteristic User Description...');myDescriptor.writeValue(encoder.encode(value)).then(_=>{log('> Characteristic User Description changed to: '+value);}).catch(error=>{log('Argh! '+error);});}