更新src后重载iframe加载旧地址异常问题求助
嵌套iframe刷新异常问题
场景概述
页面包含两层嵌套iframe:
- 顶层窗口有一个id为
containerframe的iframe,初始src设为https://www.youtube.com/watch?v=qz0aGYrrlhU containerframe内部嵌套了名为pcpFrame的iframe,通过window.parent.parent.postMessage(message, '*');向顶层窗口发送消息
顶层窗口消息监听代码
window.addEventListener('message', function (e) { // Get the sent data let iframe = window.document.getElementById("containerframe"); console.log('data json', e.data) let msg = JSON.parse(e.data) if (msg?.refresh == true){ alert("updating iframe"); iframe.src = "https://codepen.io/pen/"; // iframe.contentWindow.location.reload(true); alert("updated"); } });
预期与实际行为
- 预期行为:当收到
refresh=true的消息时,containerframe应加载新地址https://codepen.io/pen/ - 实际行为:
containerframe触发重载,但仍加载原YouTube地址,未切换到新地址
异常细节
- 非调试状态:控制台打印
iframe.src显示更新后的codepen地址,但iframe.contentDocument.location显示原YouTube地址,HTML元素面板也存在此矛盾 - 调试状态:在消息回调函数内打断点逐步执行时,
containerframe能正常加载codepen页面
内容的提问来源于stack exchange,提问作者humblefool
相关产品推荐
相关产品推荐

