Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AppleScript to choose a file in Safari

I am trying to write some automation code (primarily in Ruby Selenium). At some point, a file chooser is opened in Safari so that the user can select a file for upload. Selenium cannot handle this, but I think AppleScript should be able to. I am new to AppleScript and haven't been able to find any boilerplate code of someone automating a file chooser dialog. I'm reading through the AppleScript docs, but any ideas would be most helpful.

like image 207
Ben Flynn Avatar asked Oct 11 '22 15:10

Ben Flynn


1 Answers

Some more searching and I found a great answer here: Applescript file dialog with UI scripting

Here's what I ended up using:

on run argv
tell application "Safari"
    activate

    -- Usage check
    set argc to count argv
    if argc is not greater than 0 then
        return "Usage: SafariFileChooser file_name [window_name]"
    end if

    -- The file we will choose to open
    set file_name to item 1 of argv

    -- Flip to the named window, if specified
    if argc is equal to 2 then
        set window_name to item 2 of argv
        set flip_count to index of window window_name
        repeat (flip_count - 1) times
            activate
            tell application "System Events" to keystroke "`" using command down
        end repeat
    end if

    -- Interact with the dialog using System Events (thanks mcgrailm)
    tell front window
        activate
        tell application "System Events"
            keystroke "g" using {shift down, command down}
            keystroke file_name
            delay 1
            keystroke return
            delay 1
            keystroke return
        end tell
    end tell
end tell
return 0

end run

like image 153
Ben Flynn Avatar answered Oct 18 '22 02:10

Ben Flynn