Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

electronicsguy commented Dec 18, 2015

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

This comment has been minimized.

Copy link
Owner Author

beaufortfrancois commented Dec 21, 2015

@reillyeon

This comment has been minimized.

Copy link

reillyeon commented Jan 4, 2016

LGTM from a WebUSB perspective as well.

@larsgk

This comment has been minimized.

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
You can’t perform that action at this time.