You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AppleScript关闭chromedriver实例弹出的Chrome文件上传对话框

Selenide隐藏input文件上传问题解决方案

最优通用解决方案(从根源避免系统弹窗)

你完全不需要点击触发元素弹出系统上传对话框,通过JS修改隐藏input属性即可直接完成上传,全平台通用,不需要任何系统级脚本:

  • 直接定位input[type=file]元素,无需等待点击触发a标签渲染,只要该元素在DOM中存在(哪怕初始是隐藏状态)即可操作
  • 用JS移除元素的隐藏样式和禁用属性,直接调用Selenide上传方法即可,全程不会弹出系统对话框
// 等待文件上传input元素存在
SelenideElement fileInput = $x("//input[@type='file']").shouldBe(exist);
// 移除元素的隐藏属性和tabindex限制
executeJavaScript("arguments[0].removeAttribute('style');arguments[0].removeAttribute('tabindex');", fileInput);
// 直接上传本地文件
fileInput.uploadFile(new File("/path/to/the/uploadedFile"));
// 如需触发上传后的页面回调逻辑,手动触发change事件即可
executeJavaScript("arguments[0].dispatchEvent(new Event('change'));", fileInput);

AppleScript识别ChromeDriver启动的Chrome实例解决方案

如果要沿用你原来的AppleScript关闭弹窗的方案,失效的核心原因有两个:一是你脚本中第一个return input写在了点击Cancel逻辑之前,后续代码根本没有执行;二是硬编码窗口标题匹配不可靠,修改后的脚本参考如下:

on run {input, parameters}
    delay 3
    set timeoutSeconds to 5
    -- 不硬匹配窗口标题,直接定位Chrome进程下的所有上传弹窗
    set uiScript to "click button \"Cancel\" of sheet 1 of (first window of application process \"Google Chrome\" whose role description is \"dialog\")"
    my doWithTimeout(uiScript, timeoutSeconds)
    return input
end run

on doWithTimeout(uiScript, timeoutSeconds)
    set endDate to (current date) + timeoutSeconds
    repeat
        try
            run script "tell application \"System Events\"
" & uiScript & "
end tell"
            exit repeat
        on error errorMessage
            if ((current date) > endDate) then
                error "Can not " & uiScript
            end if
        end try
    end repeat
end doWithTimeout

另外需要在macOS「系统设置-隐私与安全性-辅助功能」中,给你运行测试的IDE/终端开启权限,否则AppleScript没有操作系统UI的权限。

Java Robot按ESC失效解决方案

macOS系统弹窗优先级极高,你按下ESC前需要先激活Chrome进程,修改后的代码如下:

try {
    Robot robot = new Robot();
    // 先激活Chrome窗口
    String[] cmd = {"/usr/bin/osascript", "-e", "tell application \"Google Chrome\" to activate"};
    Runtime.getRuntime().exec(cmd);
    Thread.sleep(1000);
    // 再按ESC关闭弹窗
    robot.keyPress(KeyEvent.VK_ESCAPE);
    robot.keyRelease(KeyEvent.VK_ESCAPE);
} catch (Exception e) {
    e.printStackTrace();
}

以上三个方案优先推荐第一种,稳定性最高且无平台依赖。

内容的提问来源于stack exchange,提问作者xakrurychle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:06:03