How do I tell if the frontmost window is a NSOpenPanel / file open dialog in MacOS using Applescript?

225 Views Asked by At

I'm trying to automatically change the directory of the frontmost "file open dialog" or NSOpenPanel dialog with AppleScript, whether that window is part of any application. The idea is that I hit a hotkey, and it will control that dialog to switch to a particular folder.

I can't seem to find out how to find the attributes of a window that would filter it for a "file open dialog". Using the Accessibility Inspector I can find that the "class" is NSOpenPanel. How can I get the class of a window using Applescript?

1

There are 1 best solutions below

5
Ted Wrigley On BEST ANSWER

If you run the following AppleScript, you can see the properties of the foremost window:

tell application "anApp" to activate
delay 1
tell application "System Events"
    tell process "anApp"
        properties of window 1
    end tell
end tell

The app has to be active to see the properties of the windows; You will not get consistent results if the app is in the background.

The NOOpenPanel ought to be recognizable by testing for some combination of the following properties:

  • role description:"dialog"
  • title:"Open"
  • subrole:"AXDialog"
  • name:"Open"
  • description:"dialog"

Personally, I'd probably rely on name and role description, which should be the same anytime an app throughs up a standard 'Open' dialog. 'Save' dialogs will be the same, except that title and name will be 'save' rather than 'open'.

If you have an app that presents a open or save sheet (a sub window attached to the titlebar), not a separate dialog, then you'll shift things a little. The AppleScript to get the properties looks like this:

tell application "anApp" to activate
delay 1
tell application "System Events"
    tell process "anApp"
        tell window 1
            properties of sheet 1
        end tell
    end tell
end tell

and the relevant testable properties are as follows:

  • accessibility description:"save"
  • role description:"sheet"
  • role:"AXSheet"
  • description:"save"

You'll probably have to add logic to test whether the front window has a sheet, which should distinguish between dialogs and sheets.

Some apps use non-standard open/save dialogs, and you'll have to account for them on a case-by-case basis. There's no magic bullet for that.