MacOS – How to quit multiple versions of Firefox with Apple Script

applescriptmacos

I have two versions of firefox. One has an application name "Firefox" and the other is called "Firefox 2".

I'd like to tell AppleScript to close both instances of Firefox. Here's my code

tell application "Firefox" to quit
tell application "Firefox 2" to quit

It's weird because I can type this into Script Editor, but when I press save it always turns into this.

tell application "Firefox" to quit
tell application "Firefox" to quit

enter image description here

I ran this code and I'll put the output below.

tell application "System Events"
    set theVisibleApps to (name of application processes where visible is true)
end tell

{"Finder", "Terminal", "Script Editor", "firefox", "firefox"}

And here's the error code: error "Firefox got an error: Connection is invalid." number -609

How do I make sure they both close?

Best Answer

I'm assuming that you made a physical. on-disk copy of Firefox.app, and renamed it in the Finder to "Firefox 2.app". Is that correct? If so, that is going to cause you headaches. The visible name in the Finder isn't really used by the system much. The system uses the app's bundle identifier — for Firefox, I believe that's something like 'org.mozilla.firefox' — which is found in the info.plist file within the app bundle, and draws display names and such from that plist also. Unix, on the other hand, tends to use the name of the executable, which is in the MacOS folder inside the app bundle. Since your physical copy will have the same bundle ID as the original, the system will get confused if you try to distinguish between the apps that way.

The normal way to run two instances of an application is to use the unix open command with the -n option, e.g., one of these:

open -n '/Applications/FireFox.app/Contents/MacOS/firefox'

open -n -g org.mozilla.firefox

Each opened instance will have the same name and bundle id, but they will have different process identifiers (pid), and you can distinguish between them using those. There are a few different ways of doing that, depending on how you've set things up, but for a quick hack in AppleScript you can use something like:

tell application "System Events"
    set unixIDs to unix id of (every process whose name is "Firefox")
end tell

Whichever unix ID is lower should generally be the instance that was launched first.