Avoid apps from stealing focus in macOS
How can I stop a program, for instance Slack, which can have some significant loading time, stealing focus when it's finished loading?
If I start Slack, then switch focus during its loading time, the program steals focus when it's done loading. It drives me nuts.
Is there a way to prevent this behavior?
I found a couple options that should cover most applications. Either one of these could be used to create an Automator workflow to make running the script more convenient.
Option 1: Terminal command
The open
command can be used to open an application using the -a
option. You can add the -g
option to open the application without bringing it to the foreground. This does not work for Slack or Google Chrome. I suspect it is because they are cross-platform applications that are built differently and aren't perfect macOS citizens. This solution is preferable if it works for the desired application.
open -g -a "Microsoft Word"
Option 2: AppleScript
You can use AppleScript to activate an application and hide it if it had not previously been running. The application will launch and still steal focus, but the script will delay a short time to ensure the application launches before trying to hide it. It's definitely not a perfect solution, but it works.
set appName to "Slack"
-- Check if the application is running
set appIsRunning to application appName is running
-- Activate the application
tell application appName to activate
if not appIsRunning then
-- If the application is not running, delay and then hide the application
delay 1 -- increase this value as needed
tell application "Finder" to set the visible of process appName to false
else
-- If the application is running, count the number of windows.
tell application "System Events" to tell process appName to set windowCount to count of windows
-- If no windows are open, open a new one.
if windowCount = 0 then
-- Open window command here. I could not find one for Slack
end if
end if
See this answer for several commands for opening new windows if that is desired.