Skip to content

Instantly share code, notes, and snippets.

@kevinjalbert
Last active June 27, 2020 02:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kevinjalbert/e39dca94b0e0eb63207479519fdfcd65 to your computer and use it in GitHub Desktop.
Save kevinjalbert/e39dca94b0e0eb63207479519fdfcd65 to your computer and use it in GitHub Desktop.
AppleScript to connect bluetooth headphones and show its battery level
activate application "SystemUIServer"
set deviceName to "Kevin Jalbert's BeatsX"
tell application "System Events"
tell process "SystemUIServer"
set bluetoothMenu to (menu bar item 1 of menu bar 1 whose description contains "bluetooth")
tell bluetoothMenu
click
set deviceMenuItem to (menu item deviceName of menu 1)
tell deviceMenuItem
click
if exists menu item "Connect" of menu 1 then
click menu item "Connect" of menu 1
return "Connecting..."
else
set batteryLevelMenuItem to (menu item 3 of menu 1)
tell batteryLevelMenuItem
set batteryLevelText to title of batteryLevelMenuItem
end tell
key code 53 -- esc key
return batteryLevelText
end if
end tell
end tell
end tell
end tell
@kevinjalbert
Copy link
Author

Hooking it all up with an Alfred workflow:

@kevinjalbert
Copy link
Author

@Lhadalo
Copy link

Lhadalo commented Sep 27, 2019

Really sweet. I hooked it up to a touchbar button, feels really slick. Thanks!

@kevinjalbert
Copy link
Author

@Lhadalo care to share how you did that? Is that still via Alfred or something else?

@Lhadalo
Copy link

Lhadalo commented Sep 30, 2019

@kevinjalbert It is via BetterTouchTool. You can execute a AppleScript as an action, so I just in pasted your script.

@kevinjalbert
Copy link
Author

Ah! Perfect.

@kekemu
Copy link

kekemu commented Jun 26, 2020

Thanks for sharing!!
I use your codes on my repository as personal purpose.
Forgive me that I use it without any asking.

@kevinjalbert
Copy link
Author

Thanks for sharing!!
I use your codes on my repository as personal purpose.
Forgive me that I use it without any asking.

No worries! Glad you got use out of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment