JavaScript打开新窗口后无法访问其document对象问题求助
根因分析
- 写入新窗口内容前没有显式打开文档流,写入完成后也未关闭文档流,导致浏览器阻塞内容渲染
- 未明确指定新窗口地址为
about:blank,部分浏览器的安全策略会拦截对空地址窗口document对象的访问
修复方案
按如下规则调整代码即可:
window.open时显式指定目标地址为about:blank- 写入内容前调用
document.open()打开文档流 - 所有内容写入完成后调用
document.close()关闭文档流触发渲染
修复后完整代码
var print_btn; let win; document.getElementsByTagName('html')[0].innerHTML = document.getElementsByTagName('html')[0].innerHTML +"<button class=\"printbuton\">Print Button</button>"; print_btn = document.getElementsByClassName('printbuton')[0]; print_btn.onclick = function() { console.log("check 1"); var WinPrint = window.open('about:blank', '', 'left=0,top=0,width=384,height=900,toolbar=0,scrollbars=0,status=0'); console.log("check 2"); WinPrint.document.open(); WinPrint.document.write('Print this'); console.log("check 3"); WinPrint.document.write('Print that'); WinPrint.document.write('and this'); WinPrint.document.close(); console.log("button pushed"); // 如需自动打印可放开以下注释 // WinPrint.focus(); // WinPrint.print(); // WinPrint.close(); }
其他注意事项
- 若调整后仍无法写入内容,可检查浏览器是否开启了弹窗拦截,或者当前站点是否配置了跨源隔离规则
- 自动打印操作需要在
document.close()执行完成后调用,避免打印空白内容
内容的提问来源于stack exchange,提问作者Veselin
相关产品推荐
相关产品推荐

