导航到其他页面时,蓝牙设备会断开连接



我正在创建一个web应用程序,其中web蓝牙需要在所有网页中配对。我可以在index.html页面上配对设备,但当导航到其他页面时,蓝牙连接断开。有没有一种方法可以在不需要重新连接的情况下再次使用相同的配对设备?我正在使用以下示例连接到设备https://googlechrome.github.io/samples/web-bluetooth/automatic-reconnect.html

代码:

<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>

Chrome目前实现的Web蓝牙无法让网站获得允许设备的列表。WIPgetDevices()将返回BluetoothDevice对象的列表,用户已授予当前来源使用这些对象的权限,以便您可以重新连接到它们。

请参阅https://www.chromestatus.com/feature/4797798639730688

下面是一些示例代码,当您在chrome://flags中启用experimental-web-platform-features标志时,您可以尝试一下。

navigator.bluetooth.getDevices()
.then(devices => {
console.log('> Got ' + devices.length + ' Bluetooth devices.');
for (const device of devices) {
console.log('  > ' + device.name + ' (' + device.id + ')');
}
})
.catch(error => {
console.log('Argh! ' + error);
});

最新更新