Skip to content

Instantly share code, notes, and snippets.

@beaufortfrancois
Last active February 14, 2024 06:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beaufortfrancois/951fc384e87a786a6d35 to your computer and use it in GitHub Desktop.
Save beaufortfrancois/951fc384e87a786a6d35 to your computer and use it in GitHub Desktop.
Web Bluetooth + Permissions API
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...
});
@electronicsguy
Copy link

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?

@beaufortfrancois
Copy link
Author

@reillyeon
Copy link

LGTM from a WebUSB perspective as well.

@larsgk
Copy link

larsgk commented Sep 4, 2018

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