applescriptwindow-management

AppleScript Managing Windows


I want to make my window to the frontmost -1. I have an application that activates Safari to run a JavaScript once every two minutes when I've been away from my computer for more than 30 minutes. However, when the script is done I want Safari to go frontmost -1. So that the same window is frontmost as it was when I left my computer.

I know that I can just hide or minimize my Safari window, but that's not what I want :-) Any ideas?


Solution

  • Rather than having Safari go frontmost minus 1, what you could do is make whatever the previous app was become frontmost. Since Safari is currently frontmost, this will make Safari frontmost minus 1.

    Here is an app that will remember the name of the current active app, activate Safari, and then return to the previous active app.

    on idle
        tell application "System Events"
            -- remember the current active app
            set currentActiveApp to first process where it is frontmost
            set activeAppName to name of currentActiveApp
    
            display notification activeAppName
    
            tell application "Safari"
                --do stuff with Safari that makes it frontmost
                activate
            end tell
    
            --make sure we have had time to switch to Safari
            repeat while (currentActiveApp is frontmost)
                delay 0.4
            end repeat
            --delay so that we can see we are in Safari
            delay 2
    
            --return to previous application
            display notification "Returning to " & activeAppName
            set frontmost of currentActiveApp to true
            delay 2
    
        end tell
    
        --do it all over in ten seconds
        return 10
    end idle