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

如何用AppleScript定位Safari的「重新加载此页面」按钮并等待页面加载

解决Safari 16.2页面加载等待的AppleScript方案

问题根源

旧代码依赖的Safari UI层级在Big Sur及更高版本中已发生变化,通过固定索引定位按钮的方式容易因工具栏按钮(如Translate)的存在而失效。

方案一:修正UI元素定位(适配Safari 16.2)

通过Accessibility Inspector(Xcode开发者工具中可找到)可确认当前Safari的Reload按钮准确路径,以下是适配后的代码:

tell application "Safari" to make new document with properties {URL:"https://nytimes.com"}
tell application "System Events"
    tell process "Safari"
        repeat until exists (button of toolbar 1 of window 1 whose accessibility description is "Reload this page")
            delay 0.5
        end repeat
        -- 双重确认:加载完成时按钮描述会从"Stop loading this page"变回"Reload this page"
        repeat until accessibility description of (button of toolbar 1 of window 1 whose accessibility description is "Reload this page") contains "Reload this page"
            delay 0.5
        end repeat
    end tell
end tell
log "Finished loading"

核心改进:

  • 直接通过accessibility description匹配按钮,避免索引变动的问题
  • 增加状态判断,确保页面从“加载中”切换为“已完成”

方案二:更稳定的非UI依赖方案(推荐)

无需依赖工具栏按钮的UI元素,直接通过Safari自身的文档属性判断加载状态,兼容性更强:

tell application "Safari"
    make new document with properties {URL:"https://nytimes.com"}
    set targetDoc to front document
    repeat while loading of targetDoc is true
        delay 0.5
    end repeat
    -- 可选:增加短延迟确保页面渲染完成
    delay 1
end tell
log "Finished loading"

优势:

  • 不依赖UI层级变化,适配所有Safari新版本
  • 直接从应用层面获取加载状态,逻辑更可靠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 21:40:25