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

如何在Google Chrome中通过AppleScript/JavaScript等待iFrame加载完成

如何在Google Chrome中使用AppleScript/JavaScript等待iFrame加载完成?

原有方案失效原因

  • 第一种方案只检测顶层页面的document.readyState,不会监听内部iframe的加载进度,顶层页面加载完成后就会终止等待,此时iframe可能还未加载完毕。
  • 第二种方案拆分了JS执行逻辑,Chrome每次调用execute javascript都是独立上下文,前一次定义的contentDocument变量会在第二次执行JS时被清除,导致判断逻辑永远不成立,陷入无限循环。

可行实现方案

把iframe状态判断逻辑合并为单次JS执行,每次轮询都重新获取iframe对象判断状态,示例代码如下:

tell application "Google Chrome"
    tell active tab of front window
        repeat
            set loadState to execute javascript "
                // 定位目标iframe,可根据实际情况修改选择器
                const targetIframe = document.querySelector('iframe');
                if (!targetIframe) return 'loading';
                if (targetIframe.contentDocument.readyState !== 'complete') return 'loading';
                // 自定义业务判断:检测目标元素是否存在,可按需修改或删除
                if (targetIframe.contentDocument.querySelectorAll('a[role=\"button\"]').length === 0) return 'loading';
                return 'complete';
            "
            if loadState = "complete" then exit repeat
            delay 0.5
        end repeat
    end tell
end tell

注意事项

  • 若页面存在多个iframe,可修改querySelector的参数为更精准的选择器(比如带ID、类名的选择器),避免定位到错误的iframe。
  • 若iframe与顶层页面跨域,Chrome默认会禁止JS访问contentDocument属性,这种场景需要给Chrome添加--disable-web-security启动参数关闭跨域限制,才能正常使用该方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:27:03