Javascript 导航到其他页面时蓝牙设备断开连接
我正在创建一个web应用程序,其中web bluetooth需要在所有网页中配对。我可以在index.html页面上对设备进行配对,但是当导航到其他页面时,蓝牙连接会断开。有没有办法在不重新连接的情况下再次使用相同的配对设备? 我正在使用以下示例连接到设备 代码:Javascript 导航到其他页面时蓝牙设备断开连接,javascript,bluetooth,webapi,web-bluetooth,Javascript,Bluetooth,Webapi,Web Bluetooth,我正在创建一个web应用程序,其中web bluetooth需要在所有网页中配对。我可以在index.html页面上对设备进行配对,但是当导航到其他页面时,蓝牙连接会断开。有没有办法在不重新连接的情况下再次使用相同的配对设备? 我正在使用以下示例连接到设备 代码: 扫描 活产量 var蓝牙设备; var ChromeSamples={ 日志:函数(){ var line=Array.prototype.slice.call(参数).map(函数(参数){ 返回typeof参数=='str
扫描
活产量
var蓝牙设备;
var ChromeSamples={
日志:函数(){
var line=Array.prototype.slice.call(参数).map(函数(参数){
返回typeof参数=='string'?参数:JSON.stringify(参数);
}).加入(“”);
document.querySelector(“#log”).textContent+=line+'\n';
},
clearLog:function(){
document.querySelector('#log').textContent='';
},
设置状态:功能(状态){
document.querySelector(“#status”).textContent=status;
},
setContent:函数(newContent){
var content=document.querySelector(“#content”);
while(content.hasChildNodes()){
content.removeChild(content.lastChild);
}
content.appendChild(newContent);
}
};
函数onButtonClick(){
bluetoothDevice=null;
日志('请求任何蓝牙设备…');
navigator.bluetooth.requestDevice({
//过滤器:[……]{
蓝牙设备=设备;
sessionStorage.lastDevice=device.id;
console.log(蓝牙设备);
日志(bluetoothDevice.id);
日志(bluetoothDevice.name);
bluetoothDevice.addEventListener('gattserverdisconnected',onDisconnected);
connect();
})
.catch(错误=>{
日志('Argh!'+错误);
});
}
函数连接(){
指数衰减(3/*最大重试次数*/,2/*秒延迟*/,
函数toTry(){
时间('连接到蓝牙设备…');
返回bluetoothDevice.gatt.connect();
},
函数成功(){
日志(“>蓝牙设备已连接。请立即尝试断开连接。”);
},
函数失败(){
时间('重新连接失败');
});
}
函数onDisconnected(){
日志(“>蓝牙设备已断开”);
connect();
}
//if(会话存储){
//navigator.permissions.query({
//名称:“蓝牙”,
//deviceId:sessionStorage.lastDevice,
//})。然后(结果=>{
//if(result.devices.length==1){
//日志(result.devices[0].id);
//日志(结果。设备[0]。名称);
//返回结果。设备[0];
//}其他{
//抛出新的DomeException(“权限丢失”、“NotFoundError”);
// }
// })
// }
/*乌提尔斯*/
//此函数一直调用“toTry”,直到promise解析或
//重试“最大”次数。第一次重试的延迟为“延迟”秒。
//“成功”就是成功。
函数指数衰减(最大、延迟、总计、成功、失败){
toTry()。然后(结果=>success(结果))
.catch(=>{
如果(最大值===0){
返回失败();
}
时间(“+delay+”重试…(“+max+”向左尝试)”;
setTimeout(函数(){
指数衰减(-max,delay*2,toTry,success,fail);
},延迟*1000);
});
}
功能时间(文本){
日志('['+newdate().toJSON().substr(11,8)+']'+text);
}
document.querySelector('button')。addEventListener('click',函数(事件){
event.stopPropagation();
event.preventDefault();
如果(isWebBluetoothEnabled()){
ChromeSamples.clearLog();
onButtonClick();
}
});
log=ChromeSamples.log;
函数isWebBluetoothEnabled(){
如果(导航器.蓝牙){
返回true;
}否则{
ChromeSamples.setStatus('Web蓝牙API不可用。\n'+
'请确保启用了“实验Web平台功能”标志。');
返回false;
}
}
Chrome当前的Web Bluetooth实现无法让网站获取允许的设备列表。WIPgetDevices()
将返回一个BluetoothDevice对象列表,当前源设备已被用户授予使用权限,以便您可以重新连接到它们
看
下面是一些示例代码,当您今天在chrome://flags
尝试一下
navigator.bluetooth.getDevices()
。然后(设备=>{
log('>get'+devices.length+'Bluetooth devices');
用于(设备中的常量设备){
console.log('>'+device.name+'('+device.id+'));
}
})
.catch(错误=>{
console.log('Argh!'+错误);
});
请尝试解释一下您所做的工作。并提出一些代码。@Abilogos添加了代码示例。
<ul><a href="page1.html">page1</a></ul>
<ul><a href="page2.html">page2</a></ul>
<ul><a href="page3.html">page3</a></ul>
<form>
<button>Scan</button>
</form>
<h3>Live Output</h3>
<div id="output" class="output">
<div id="content"></div>
<div id="status"></div>
<pre id="log"></pre>
</div>
<script>
var bluetoothDevice;
var ChromeSamples = {
log: function() {
var line = Array.prototype.slice.call(arguments).map(function(argument) {
return typeof argument === 'string' ? argument : JSON.stringify(argument);
}).join(' ');
document.querySelector('#log').textContent += line + '\n';
},
clearLog: function() {
document.querySelector('#log').textContent = '';
},
setStatus: function(status) {
document.querySelector('#status').textContent = status;
},
setContent: function(newContent) {
var content = document.querySelector('#content');
while(content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
content.appendChild(newContent);
}
};
function onButtonClick() {
bluetoothDevice = null;
log('Requesting any Bluetooth Device...');
navigator.bluetooth.requestDevice({
// filters: [...] <- Prefer filters to save energy & show relevant devices.
acceptAllDevices: true})
.then(device => {
bluetoothDevice = device;
sessionStorage.lastDevice = device.id;
console.log(bluetoothDevice);
log(bluetoothDevice.id);
log(bluetoothDevice.name);
bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);
connect();
})
.catch(error => {
log('Argh! ' + error);
});
}
function connect() {
exponentialBackoff(3 /* max retries */, 2 /* seconds delay */,
function toTry() {
time('Connecting to Bluetooth Device... ');
return bluetoothDevice.gatt.connect();
},
function success() {
log('> Bluetooth Device connected. Try disconnect it now.');
},
function fail() {
time('Failed to reconnect.');
});
}
function onDisconnected() {
log('> Bluetooth Device disconnected');
connect();
}
// if (sessionStorage) {
// navigator.permissions.query({
// name: "bluetooth",
// deviceId: sessionStorage.lastDevice,
// }).then(result => {
// if (result.devices.length == 1) {
// log(result.devices[0].id);
// log(result.devices[0].name);
// return result.devices[0];
// } else {
// throw new DOMException("Lost permission", "NotFoundError");
// }
// })
// }
/* Utils */
// This function keeps calling "toTry" until promise resolves or has
// retried "max" number of times. First retry has a delay of "delay" seconds.
// "success" is called upon success.
function exponentialBackoff(max, delay, toTry, success, fail) {
toTry().then(result => success(result))
.catch(_ => {
if (max === 0) {
return fail();
}
time('Retrying in ' + delay + 's... (' + max + ' tries left)');
setTimeout(function() {
exponentialBackoff(--max, delay * 2, toTry, success, fail);
}, delay * 1000);
});
}
function time(text) {
log('[' + new Date().toJSON().substr(11, 8) + '] ' + text);
}
document.querySelector('button').addEventListener('click', function(event) {
event.stopPropagation();
event.preventDefault();
if (isWebBluetoothEnabled()) {
ChromeSamples.clearLog();
onButtonClick();
}
});
log = ChromeSamples.log;
function isWebBluetoothEnabled() {
if (navigator.bluetooth) {
return true;
} else {
ChromeSamples.setStatus('Web Bluetooth API is not available.\n' +
'Please make sure the "Experimental Web Platform features" flag is enabled.');
return false;
}
}
</script>