作者:林友昂
链接:https://www.zhihu.com/question/30884733/answer/104715177
来源:知乎
著作权归作者所有,转载请联系作者获得授权。
以下是以上链接介绍的简单列子
Here is a very simple example, showing a button:
<button id="the-button">Try it</button>
…and the following JavaScript:
const button = document.querySelector('#the-button');
button.addEventListener('click', function() {
navigator.bluetooth.requestDevice({
filters: [{
services: ['battery_service']
}]
}).then(device => {
console.log('Got device:', device.name);
console.log('id:', device.id);
});
});
As mentioned earlier, the method navigator.bluetooth.requestDevice() can only be called in response to a user action like a button click. This method calls up a dialog box showing the list of available BLE devices matching the query filter. In our case, the filter we have set pertains to BLE devices which expose a so-called “GATT service” called battery_service. We’ll find out more about GATT services in the next section.
可试下