Web Bluetooth:如何用JavaScript检测蓝牙是否开启及状态变化?
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
trueif the user's device has Bluetooth hardware (radio) installed - It resolves to
falseif 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

