Is there any way in AppleScript, or from the CLI, to get the name of the current Desktop/Space?

I use Keyboard Maestro to perform some actions. It would be useful if I could get the name of the current Mission Control Desktop/Space (For me 'Desktop 1' to 'Desktop 8') so that when the script ends I can then flip back to wherever I was before.


I would ideally like a way to do it in either AppleScript or a CLI/BASH, or if the value is available in a file anywhere?


Currently trying to use the Mission Control swipe up to show the desktop/space names and then use the found image in KM but it is very hit and miss for some reason. There must be a better way surely!

Posted on Feb 15, 2023 4:40 AM

Reply
Question marked as Top-ranking reply

Posted on Feb 15, 2023 10:30 AM

Never mind, found it.


There is a wonderful app on github called WhichSpace (https://github.com/gechr/WhichSpace), then I use:


tell application "System Events" to tell process "WhichSpace" to set temp to (title of menu bar items of menu bar 1)
return item 1 of temp


Credit for the AppleScript to Jim Sauer on the Keyboard Maestro forums (https://forum.keyboardmaestro.com/t/macros-desktop-spaces-macros-to-improve-navigation-and-window-management-v1-1/27033).



2 replies
Question marked as Top-ranking reply

Feb 15, 2023 10:30 AM in response to Mark Armitage

Never mind, found it.


There is a wonderful app on github called WhichSpace (https://github.com/gechr/WhichSpace), then I use:


tell application "System Events" to tell process "WhichSpace" to set temp to (title of menu bar items of menu bar 1)
return item 1 of temp


Credit for the AppleScript to Jim Sauer on the Keyboard Maestro forums (https://forum.keyboardmaestro.com/t/macros-desktop-spaces-macros-to-improve-navigation-and-window-management-v1-1/27033).



Feb 15, 2023 10:56 AM in response to Mark Armitage

I'm not aware of any way to determine this, which seems like a gap... I'll keep poking.


In the meantime, a workaround may be to capture the current application at the beginning of your script, and simply 'activate' that application at the end - assuming you have the preferences set to switch to the space for the current app.


tell application "System Events"
	set startingApp to first application process whose frontmost is true
	
	-- do your stuff
	
	tell application startingApp to activate
end tell


This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Is there any way in AppleScript, or from the CLI, to get the name of the current Desktop/Space?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.