It it possible to detect application focus event using applescript? What I'm trying to achieve is to open ios simulator when I focus on text editor. I know how to activate simulator but can't figure out how to detect when the editor is active.
A simple solution, using AppleScripts immanent capacities
[I am a little ashamed to admit that due to an "unhappy localisation" I did not realise there is a perfectly suitable way to make AS-scripts repeat periodically. The English term "Stay Open Application" in its German version ominously re-translates to "Display after run-handler". ]
(I will leave parts of my workaround solution at the bottom, because of its own merit.)
on idle tell application "System Events" if frontmost of process "TextEdit" is true then ¬ tell application "name_of_simulator" to activate return 2 -- this number tells System at what intervals to execute end tell end idle
… is really all you need.
Save this code in ScriptEditor, check "Stay Open" application (or similar) and run the app.
(Close ScriptEditor if you like.)
"Working solution" to detect change of frontmost application
[ … ] AppleScript's problem is the "timing"… <== WRONG !!!
In order to display my current workspace's index in the right-side menu bar (as in older OSX versions:
) I use –and recommend!– Mat Ryer's app "BitBar" that lets you place any script in its plugins folder. Their names, e.g. "workspace.2s.sh", cleverly determine the interval between executions of the script: "2s" denoting every two seconds (minutes, hours, days…).
#!/bin/bash _/¯ osascript /Users/userName/.config/bitbar/Workspace.appcalls a script that compares my desktop picture to a stored list and so returns my workspace number.