Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppleScript, quit an app by id, safely

Tags:

applescript

It's possible to run multiple instances or copies of the same app on a Mac. But AppleScript can't seem to identify them separately. Say my app is "FileMaker Pro" and I have multiple copies of it running. Having AppleScript tell "FileMaker Pro" to quit, I believe quits the first one that ran, which might not be the one I want it to quit.

I want to write a script that first will identify the frontmost application, then go off and do some other stuff (which might bring other apps to the front) then SAFELY quit the original frontmost application that it identified at the start.

Some googling I've done has found suggestions where I identify the the frontmost application by process id and then

do shell script "kill ..."

but from what I can tell "kill" doesn't ask to save changes, etc. (so it doesn't SAFELY quit").

I want this script to do exactly what the AppleScript quit command or manually choosing quit from the file menu would do, including ask to save changes or whatever else.

Is this possible? If so how?

like image 331
DavidT Avatar asked Oct 16 '25 09:10

DavidT


1 Answers

For a copy of an application: it's possible by using the path of the application instead of the name.

tell application "System Events"
    tell (first application process whose frontmost is true)
        set x to its application file -- get the path of this application (the result is an alias of "System Events")
    end tell
    set thisAppPath to path of x -- get the path (a string)
end tell

--- ***  go off and do some other stuff ****
---


--- SAFELY quit the original frontmost application that it identified at the start.
tell application thisAppPath -- the path must be a string
    try -- *** use 0 to no limit    ***
        with timeout of 240 seconds -- a time limit is given to the user to save changes, etc.
            quit
        end timeout
    on error -- (timeout error): the user do nothing because the application is still open
        -- do something
    end try
end tell
--
-- script after the application quits
--
like image 115
jackjr300 Avatar answered Oct 19 '25 12:10

jackjr300



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!