Bluetooth.requestDevice() - Web APIs 编辑

Secure context

This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Experimental

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The Bluetooth.requestDevice() method of the Bluetooth interface returns a Promise to a BluetoothDevice object with the specified options. If there is no chooser UI, this method returns the first device matching the criteria.

Syntax

Bluetooth.requestDevice([options])
  .then(function(bluetoothDevice) { ... })

Returns

A Promise to a BluetoothDevice object.

Parameters

options Optional
An object that sets options for the device request. The available options are:
  • filters[]: An array of BluetoothScanFilters. This filter consists of an array of  BluetoothServiceUUIDs, a name parameter, and a namePrefix parameter.
  • optionalServices[]: An array of BluetoothServiceUUIDs.
  • acceptAllDevices: A Boolean indicating that the requesting script can accept all Bluetooth devices. The default is false.

Exceptions

TypeError
The provided options do not makes sense. For example, options.filters is present and options.acceptAllDevices is true, or if options.filters is not present and options.acceptAllDevices is false. Or options.filters is [].
NotFoundError
There is no Bluetooth device that matches the specified options.
SecurityError
This operation is not permitted in this context due to security concerns. For example, it is called from insecure origin.

Example

// Discovery options match any devices advertising:
// . The standard heart rate service.
// . Both 16-bit service IDs 0x1802 and 0x1803.
// . A proprietary 128-bit UUID service c48e6067-5295-48d3-8d5c-0395f61792b1.
// . Devices with name "ExampleName".
// . Devices with name starting with "Prefix".
//
// And enables access to the battery service if devices
// include it, even if devices do not advertise that service.
let options = {
  filters: [
    {services: ['heart_rate']},
    {services: [0x1802, 0x1803]},
    {services: ['c48e6067-5295-48d3-8d5c-0395f61792b1']},
    {name: 'ExampleName'},
    {namePrefix: 'Prefix'}
  ],
  optionalServices: ['battery_service']
}

navigator.bluetooth.requestDevice(options).then(function(device) {
  console.log('Name: ' + device.name);
  // Do something with the device.
})
.catch(function(error) {
  console.log("Something went wrong. " + error);
});

Detailed examples are in the specification.

Specifications

SpecificationStatusComment
Web Bluetooth
The definition of 'requestDevice()' in that specification.
DraftInitial definition.

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:135 次

字数:5141

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文