Chrome中window.open子窗口onload函数提前执行问题求助
解决方案:让子窗口DOM加载完成后自动执行函数
原代码中直接绑定newWindow.document.body.onload会出现函数立即执行的问题,本质是子窗口的document对象还未完全初始化,此时访问并绑定事件会触发意外执行,且无法准确监听DOM加载完成的时机。以下是几种可靠的解决方式:
方式1:监听子窗口的window.onload事件
直接给子窗口的window对象绑定onload事件,这会等待整个页面(包括资源)加载完成后触发,是最稳妥的方式:
let newWindow; function tweetGet(url) { newWindow = window.open(url,'_blank',"status,height=600,width=800"); const parsefn = function() { const tweet = [url]; tweet.push(newWindow.document.querySelectorAll("time")[0].getAttribute("datetime")); newWindow.close(); console.log(tweet); } // 绑定子窗口的window.onload事件 newWindow.onload = parsefn; } tweetGet("https://x.com/VillaCollegeMv/status/1817893326437425374")
方式2:监听子窗口的DOMContentLoaded事件
如果只需要等待DOM加载完成(无需等待图片等资源),可以使用DOMContentLoaded事件,触发时机更早:
let newWindow; function tweetGet(url) { newWindow = window.open(url,'_blank',"status,height=600,width=800"); const parsefn = function() { const tweet = [url]; tweet.push(newWindow.document.querySelectorAll("time")[0].getAttribute("datetime")); newWindow.close(); console.log(tweet); } // 监听DOMContentLoaded事件 newWindow.addEventListener('DOMContentLoaded', parsefn); } tweetGet("https://x.com/VillaCollegeMv/status/1817893326437425374")
注意事项
- 避免在子窗口
document未初始化时直接访问其属性,上述两种方式都是绑定在子窗口的window对象上,能确保事件绑定在窗口加载流程的正确阶段。 - 若遇到子窗口加载异常(如跳转),可以额外添加
error事件监听做容错处理。
内容的提问来源于stack exchange,提问作者Riyaz Mansoor
相关产品推荐
相关产品推荐

