This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

The Web Bluetooth API is an API that allows Web sites to communicate with nearby low-power Bluetooth (BLE) devices selected by users for security and privacy protection through the Generic Attribute Profile (GATT) client.

Wikipedia:

  • BLE. Bluetooth Low Energy Bluetooth Low Energy (Bluetooth LE, BLE, old trademark Bluetooth Smart) is a personal LAN technology designed and marketed by the Bluetooth Technology Alliance. Aiming at emerging applications in the fields of health care, sports and fitness, beacons, security, home entertainment, etc. Compared to classical Bluetooth, low power Bluetooth aims to significantly reduce power consumption and cost while maintaining the same communication range.
  • GATT is a general specification for sending and receiving very short data segments, called attributes, over bluetooth connections. said
  • The Web Bluetooth API is based on the Promise specification.

It is still in the experimental stage, so please check the browser compatibility table carefully before using it in production. The compatibility of Can I Use is as follows:

Note: This API is not available in Web Workers.

Basic usage

Below, we’ll use a simple example to see how to get basic information about a BLE device.

Note: We hand-write a configuration option locally for ease of implementation.

We use the navigator. Bluetooth. RequestDevice () method and function to provide a configuration object, the object contain about which equipment we should use, and what are the services of the available information. It will return a Promise object. If there is no Bluetooth device selection screen, this method returns the first device that matches the condition.

<button class="btn">点我!</button>
Copy the code
let options = { filters: [ { services: ['heart_rate'] }, { services: [0x1802, 0x1803] }, { services: [' c48e6067-5295-48D3-8D5C-0395F61792B1 ']}, {name: 'device name'}, {namePrefix: 'prefix'}], Option Services: ['battery_service'] } const button = document.querySelector('.btn') button.addEventListener('click', function () { navigator.bluetooth .requestDevice(options) .then(device => { console.log('Got device:', Device. The name) / / implement equipment call}). Here the catch ((err) = > {the console. The log (" Error: "+ err)})})Copy the code

The general effect is as follows:

Error: SecurityError: requestDevice() called from cross-origin iframe -> requestDevice() called from cross-origin iframe

More resources

There are already plenty of examples to work with and learn from, and you can check out more examples at demos or Web Bluetooth Samples: Web Bluetooth printers, LED displays, racing cars, and more.

Controlling Bluetooth devices over the Web: Getting Started with WebBluetooth

Web Bluetooth API exploration