当动态改变`
在使用HTML
然而,当
考虑以下场景:
初始HTML结构:
index.html 或 indexv2.html 内部脚本:
父页面尝试调用:
function viewReport(useV2) {
const iframe = document.getElementById("the-frame");
// 如果取消注释此行,printReport() 将变为 undefined
// if (useV2)
// iframe.src = "/indexv2.html"; // 动态改变s
rc
iframe.contentWindow.printReport(); // 此时可能报错
closePrintOptions();
}当iframe.src被修改为/indexv2.html后,如果父页面立即执行iframe.contentWindow.printReport(),就会遇到printReport is undefined的错误。这是因为在iframe.src改变的那一刻,浏览器开始加载新的文档,但这个过程需要时间。在新的文档加载并执行其脚本之前,contentWindow对象尚未更新以反映新文档的全局环境。
解决这个问题的关键在于确保在父页面尝试与
以下是修正后的代码示例:
function viewReport(reportFile) {
const iframe = document.getElementById("the-frame");
// 如果提供了新的文件路径,则动态改变iframe的src
if (reportFile) {
iframe.src = reportFile; // 改变src会触发加载
// 关键:等待iframe内容加载完成
iframe.onload = function () {
// 此时,新的文档已加载完毕,可以安全地访问其contentWindow
if (iframe.contentWindow && typeof iframe.contentWindow.printReport === 'function') {
iframe.contentWindow.printReport();
} else {
console.error("Iframe content not ready or printReport function not found.");
}
closePrintOptions();
// 一次*件,执行后可以移除监听器,避免重复触发
iframe.onload = null;
};
} else {
// 如果没有改变src,直接调用(假设内容已加载)
if (iframe.contentWindow && typeof iframe.contentWindow.printReport === 'function') {
iframe.contentWindow.printReport();
} else {
console.error("Iframe content not ready or printReport function not found.");
}
closePrintOptions();
}
}动态修改