如何检测Google Maps iframe是否完成加载及加载动画
Google Maps iframe 加载状态检测方案
核心逻辑
Google Maps 嵌入iframe默认懒加载特性是仅进入视口才开始加载,加载完成会触发原生load事件,之后500ms内加载动画会完全消失。结合jQuery的Deferred能力实现异步等待,比固定等待10秒可大幅缩减CI流水线耗时。
jQuery实现方案(可直接在CodeceptJS中使用)
通用兼容版(跨域/同域都支持)
该版本适配公开嵌入的Google Maps iframe默认跨域无法访问内部DOM的场景,采用load事件兜底+超时保护,完全满足视觉回归测试的精度要求:
// 直接在CodeceptJS的executeAsyncScript中运行即可 function waitForGoogleMapsLoad() { const dfd = $.Deferred(); // 匹配所有Google Maps嵌入iframe const $mapIframe = $('iframe[src*="google.com/maps/embed"]'); // 页面无匹配iframe直接返回成功 if ($mapIframe.length === 0) { return dfd.resolve().promise(); } // 超时兜底,最长等待8秒(可根据业务场景调整时长 const timeoutTimer = setTimeout(() => { dfd.resolve(); }, 8000); // iframe资源全部加载完成触发 $mapIframe.on('load', () => { // 额外等待500ms确保加载动画完全结束无残影 setTimeout(() => { clearTimeout(timeoutTimer); dfd.resolve(); }, 500); }); // 处理已经加载完成的iframe直接返回 if ($mapIframe[0].contentWindow?.document.readyState === 'complete') { clearTimeout(timeoutTimer); dfd.resolve(); } return dfd.promise(); }
同域部署专属优化版
如果你的Google Maps是同域部署的,可直接访问内部DOM,实现更精准的动画结束检测,无需额外等待固定500ms:
function waitForGoogleMapsLoad() { const dfd = $.Deferred(); const $mapIframe = $('iframe[src*="google.com/maps/embed"]'); if ($mapIframe.length === 0) return dfd.resolve().promise(); const timeoutTimer = setTimeout(() => dfd.resolve(), 8000); // 每300ms轮询检测加载状态 const checkTimer = setInterval(() => { try { const iframeDoc = $mapIframe[0].contentWindow.document; // 页面加载完成且无加载动画元素即判定加载结束 if (iframeDoc.readyState === 'complete' && !iframeDoc.querySelector('.gm-loading')) { clearInterval(checkTimer); clearTimeout(timeoutTimer); dfd.resolve(); } } catch (err) { // 跨域报错自动降级到通用版逻辑 clearInterval(checkTimer); $mapIframe.on('load', () => { setTimeout(() => { clearTimeout(timeoutTimer); dfd.resolve(); }, 500); }); } }, 300); return dfd.promise(); }
CodeceptJS 测试用例调用方式
// 先滚动到底部触发iframe加载 I.scrollToPageBottom(); // 等待Google Maps加载完成 I.executeAsyncScript(() => { return waitForGoogleMapsLoad(); }); // 执行截图操作 I.saveScreenshot('page-after-maps-loaded.png');
内容的提问来源于stack exchange,提问作者NextThursday
相关产品推荐
相关产品推荐

