javascript - Web蓝牙API:Origin不允许访问服务
问题描述
我正在使用网络蓝牙 API 来连接 BLE 设备。它在https://localhost上完美运行。但是,当我在也位于 https 上的实时服务器上尝试它时,或者当我在http://locahost上尝试它时,它会通过我这个错误“Origin is not allowed to access the service. Tip: Add the service UUID to 'optionalServices ' 在 requestDevice() 选项中。”。代码如下。我已经添加了可选服务。
scanDevices () {
if(navigator.bluetooth) {
navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalService: ['0000fee0-0000-1000-8000-00805f9b34fb', '0000fee1-0000-1000-8000-00805f9b34fb']
})
.then(device => {
// save the device returned so you can disconnect later:
this.device = device;
this.device.addEventListener('gattserverdisconnected', this.onDisconnected);
// connect to the device once you find it:
return this.connect();
})
.then((server) => {
this.server = server;
return server;
})
.catch(function(error) {
// catch any errors:
console.error('Connection failed!', error);
});
} else {
this.errorMessage = 'Your browser does not support web bluetooth API.';
}
},
connect(){
let connection = this.device.gatt.connect();
console.log('Connected', connection);
return connection;
},
readData (){
this.isLoader = true;
console.log('get the primary service:');
console.log(this.server);
this.server.getPrimaryService(this.parsedService)
.then((service) => {
console.log('get the characteristic:');
return service.getCharacteristic(this.parsedCharacteristic);
})
.then(characteristic => {
return characteristic.readValue();
})
.then(value => {
console.log(value);
this.isLoader = false;
let decoder = new TextDecoder('utf-8');
console.log(decoder.decode(value));
})
.catch(error => {
this.isLoader = false;
this.errorMessage = error.message;
});
},
解决方案
似乎它缺少一个“s” optionalService
。应该是optionalServices
根据https://webbluetoothcg.github.io/web-bluetooth/#dom-requestdeviceoptions-optionalservices
推荐阅读
- javascript - 使用javascript将对象转换为对象数组
- jenkins - 在 Kubernetes 集群上安装 JenkinsX - 未通过合规性测试
- python - 将单个日志文件限制为特定大小
- raku - 为什么向类型添加方法与在 perl6 中添加子或运算符不同?
- php - 从具有变化价格的 Woocommerce 可变产品下拉列表中排除产品
- linux - 有没有办法用golang将PDF转换为jpeg?
- r - R 使用 lapply() 填充和命名数据框列表中的一列
- c++ - C++ if 语句:第一个条件取代第二个 - UB 还是定义明确?
- xml - 将一个节点的子节点复制到另一个节点,但在基于匹配的单独节点中?
- android - ActivityCompat.requestPermissions 时活动被破坏