Last active
February 14, 2024 06:17
-
-
Save beaufortfrancois/951fc384e87a786a6d35 to your computer and use it in GitHub Desktop.
Web Bluetooth + Permissions API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function connectDevice(device) { | |
return device.connectGATT() | |
.then(...) | |
} | |
// Simple | |
permissions.query({ name: 'bluetooth' }) | |
.then(permission => { | |
if (permission.state != 'granted') { | |
console.log('User has forbidden websites to use bluetooth...'); | |
return; | |
} | |
if (permission.referringDevice) { | |
// Let's try to connect to the Physical Web object first. | |
return connectDevice(permission.referringDevice); | |
} | |
if (permission.devices.length != 0) { | |
// Some Bluetooth devices are already allowed to interact with this website. | |
// Let's try to connect to all of them. | |
return Promise.all(permission.devices.map(device => connectDevice)); | |
} | |
// Prompt user to pick a nearby hearth rate sensor. | |
return permissions.request({ name: 'bluetooth', filters: [{ services: ['heart_rate'] }] }) | |
.then(result => { | |
if (result.state != 'granted') { | |
return; | |
} | |
// Let's try to connect to the heart rate sensor. | |
return connectDevice(result.devices[0]); | |
}); | |
}); | |
// Restore | |
permissions.query({ name: 'bluetooth', deviceId: '123' }) | |
.then(permission => { | |
if (permission.state != 'granted') { | |
console.log('User has forbidden websites to use bluetooth...'); | |
return; | |
} | |
if (permission.devices.length != 0) { | |
// My previously connected Bluetooth device is still there. | |
// Let's try to connect to it. | |
return connectDevice(permission.devices[0]); | |
} | |
console.log('Previous Bluetooth device access has been revoked.'); | |
// Proceed to regular workflow as above... | |
}); | |
The filters
attribute is actually the same as http://webbluetoothcg.github.io/web-bluetooth/#dictdef-bluetoothscanfilter
LGTM from a WebUSB perspective as well.
Any news on this one? - it would be nice to be able to reconnect :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you think the BT version would be helpful in the filter? What if the user only wants to connect to BT 4.0 devices?