macos - 使用 AppleScript 在 Safari 中选择文件

标签 macos safari applescript

我正在尝试编写一些自动化代码(主要是在 Ruby Selenium 中)。有时,Safari 中会打开文件选择器,以便用户可以选择要上传的文件。 Selenium 无法处理这个问题,但我认为 AppleScript 应该可以。我是 AppleScript 新手,无法找到自动执行文件选择器对话框的任何样板代码。我正在阅读 AppleScript 文档,但任何想法都会非常有帮助。

最佳答案

更多搜索,我在这里找到了一个很好的答案:Applescript file dialog with UI scripting

这是我最终使用的:

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

结束运行

关于macos - 使用 AppleScript 在 Safari 中选择文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5170142/

相关文章:

python - 在非 Windows 平台(Linux 或 Mac)上使用 Python 中的 Access 数据库

macos - 使用 CMAKE_MACOSX_RPATH 链接构建树外部的库

ios - 为什么 `init` 不能用在 `NSCalendar *cal = [[NSCalendar alloc] init]` 中?

macos - 使用 Applescript 根据当前选择更改 Finder 上下文菜单项的名称

cocoa - 如何以编程方式将一个 Terminal.app 窗口移动到另一个空间?

c++ - 编译期间无法从 Accelerate Framework 链接 BLAS -OS Yosemite 10.0.5

java - Jenkins 用户未启用 Safari WebDriver 扩展

google-chrome - 循环播放网络音频

safari - 在 iOS 6 上的 Safari 上授权使用 JS 客户端 API 库时,是否可以支持多个 Google 帐户?

macos - AppleScript 以最前面的应用程序为目标