You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript打开新窗口后无法访问其document对象问题求助

根因分析

  • 写入新窗口内容前没有显式打开文档流,写入完成后也未关闭文档流,导致浏览器阻塞内容渲染
  • 未明确指定新窗口地址为about:blank,部分浏览器的安全策略会拦截对空地址窗口document对象的访问

修复方案

按如下规则调整代码即可:

  1. window.open时显式指定目标地址为about:blank
  2. 写入内容前调用document.open()打开文档流
  3. 所有内容写入完成后调用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:15:03