Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useBluetooth.md
1---2category: Browser3---45# useBluetooth67Reactive [Web Bluetooth API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API). Provides the ability to connect and interact with Bluetooth Low Energy peripherals.89The Web Bluetooth API lets websites discover and communicate with devices over the Bluetooth 4 wireless standard using the Generic Attribute Profile (GATT).1011N.B. It is currently partially implemented in Android M, Chrome OS, Mac, and Windows 10. For a full overview of browser compatibility please see [Web Bluetooth API Browser Compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API#browser_compatibility)1213N.B. There are a number of caveats to be aware of with the web bluetooth API specification. Please refer to the [Web Bluetooth W3C Draft Report](https://webbluetoothcg.github.io/web-bluetooth/) for numerous caveats around device detection and connection.1415N.B. This API is not available in Web Workers (not exposed via WorkerNavigator).1617## Usage Default1819```vue20<script setup lang="ts">21import { useBluetooth } from '@vueuse/core'2223const {24isSupported,25isConnected,26device,27requestDevice,28server,29error,30} = useBluetooth({31acceptAllDevices: true,32})33</script>3435<template>36<button @click="requestDevice()">37Request Bluetooth Device38</button>39<div v-if="error">40Error: {{ error }}41</div>42</template>43```4445### Return Values4647| Property | Type | Description |48| --------------- | -------------------------------- | ------------------------------------------ |49| `isSupported` | `ComputedRef<boolean>` | Whether the Web Bluetooth API is supported |50| `isConnected` | `Ref<boolean>` | Whether a device is currently connected |51| `device` | `Ref<BluetoothDevice>` | The connected Bluetooth device |52| `server` | `Ref<BluetoothRemoteGATTServer>` | The GATT server for the connected device |53| `error` | `Ref<unknown>` | Any error that occurred during connection |54| `requestDevice` | `() => Promise<void>` | Function to request a Bluetooth device |5556When the device has paired and is connected, you can then work with the server object as you wish.5758## Usage Battery Level Example5960This sample illustrates the use of the Web Bluetooth API to read battery level and be notified of changes from a nearby Bluetooth Device advertising Battery information with Bluetooth Low Energy.6162Here, we use the characteristicvaluechanged event listener to handle reading battery level characteristic value. This event listener will optionally handle upcoming notifications as well.6364```vue65<script setup lang="ts">66import { useBluetooth, useEventListener, watchPausable } from '@vueuse/core'6768const {69isSupported,70isConnected,71device,72requestDevice,73server,74} = useBluetooth({75acceptAllDevices: true,76optionalServices: [77'battery_service',78],79})8081const batteryPercent = ref<undefined | number>()8283const isGettingBatteryLevels = ref(false)8485async function getBatteryLevels() {86isGettingBatteryLevels.value = true8788// Get the battery service:89const batteryService = await server.getPrimaryService('battery_service')9091// Get the current battery level92const batteryLevelCharacteristic = await batteryService.getCharacteristic(93'battery_level',94)9596// Listen to when characteristic value changes on `characteristicvaluechanged` event:97useEventListener(batteryLevelCharacteristic, 'characteristicvaluechanged', (event) => {98batteryPercent.value = event.target.value.getUint8(0)99}, { passive: true })100101// Convert received buffer to number:102const batteryLevel = await batteryLevelCharacteristic.readValue()103104batteryPercent.value = await batteryLevel.getUint8(0)105}106107const { stop } = watchPausable(isConnected, (newIsConnected) => {108if (!newIsConnected || !server.value || isGettingBatteryLevels.value)109return110// Attempt to get the battery levels of the device:111getBatteryLevels()112// We only want to run this on the initial connection, as we will use an event listener to handle updates:113stop()114})115</script>116117<template>118<button @click="requestDevice()">119Request Bluetooth Device120</button>121</template>122```123124More samples can be found on [Google Chrome's Web Bluetooth Samples](https://googlechrome.github.io/samples/web-bluetooth/).125126## Type Declarations127128```ts129export interface UseBluetoothRequestDeviceOptions {130/**131*132* An array of BluetoothScanFilters. This filter consists of an array133* of BluetoothServiceUUIDs, a name parameter, and a namePrefix parameter.134*135*/136filters?: BluetoothLEScanFilter[] | undefined137/**138*139* An array of BluetoothServiceUUIDs.140*141* @see https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTService/uuid142*143*/144optionalServices?: BluetoothServiceUUID[] | undefined145}146export interface UseBluetoothOptions147extends UseBluetoothRequestDeviceOptions, ConfigurableNavigator {148/**149*150* A boolean value indicating that the requesting script can accept all Bluetooth151* devices. The default is false.152*153* !! This may result in a bunch of unrelated devices being shown154* in the chooser and energy being wasted as there are no filters.155*156*157* Use it with caution.158*159* @default false160*161*/162acceptAllDevices?: boolean163}164export declare function useBluetooth(165options?: UseBluetoothOptions,166): UseBluetoothReturn167export interface UseBluetoothReturn extends Supportable {168isConnected: Readonly<ShallowRef<boolean>>169device: ShallowRef<BluetoothDevice | undefined>170requestDevice: () => Promise<void>171server: ShallowRef<BluetoothRemoteGATTServer | undefined>172error: ShallowRef<unknown | null>173}174```175