You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web Bluetooth:如何用JavaScript检测蓝牙是否开启及状态变化?

Can JavaScript detect if Bluetooth is enabled, and are there events for Bluetooth state changes?

Hey there! Let's break down how you can handle this with the Web Bluetooth API:

Checking Bluetooth hardware availability (not if it's turned on)

The Web Bluetooth API includes a getAvailability() method that returns a Promise. Here's what you need to know about it:

  • It resolves to true if the user's device has Bluetooth hardware (radio) installed
  • It resolves to false if there's no Bluetooth hardware at all

A critical thing to note: this method doesn't reflect whether Bluetooth is turned on or off in system settings. Even if Bluetooth is disabled, getAvailability() will still return true as long as the hardware exists. That's intentional—when you call requestDevice() later, the browser will automatically prompt the user to turn on Bluetooth if it's off.

Detecting changes to Bluetooth availability

Yes, there's an availabilitychanged event you can listen for. This event triggers when the system's Bluetooth hardware presence changes—for example, if a user connects or disconnects an external Bluetooth adapter.

Just like getAvailability(), this event won't fire when the user toggles Bluetooth on/off in system settings—only when the hardware itself is added or removed.

How to use this in your app

This API is perfect for deciding whether to show Bluetooth-related UI elements. If getAvailability() returns false, you can safely hide any Bluetooth features since the device can't support them. If it returns true, you can proceed to use requestDevice() (which handles prompting the user to enable Bluetooth if needed).

The big limitation to keep in mind

As I mentioned earlier: you can't use getAvailability() or availabilitychanged to directly detect if Bluetooth is actively turned on. They only check for the presence of Bluetooth hardware. So if you need to know if Bluetooth is enabled, you'll have to rely on the requestDevice() flow to prompt the user to turn it on if necessary.

内容的提问来源于stack exchange,提问作者Igor Alemasow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:17:54