如何在window.open()时移除about:blank并显示加载提示?
需求完全可行,这是实现方案
你可以直接往window.open()返回的窗口对象里写入自定义的加载提示HTML,替换默认的about:blank页面。具体修改如下:
修改后的代码:
const windowReference = window.open(); if (windowReference) { // 立即写入加载提示的HTML内容 windowReference.document.write(` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>加载中...</title> <style> body { margin: 0; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-family: Arial, sans-serif; background-color: #f5f5f5; } .loader { border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin-bottom: 16px; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style> </head> <body> <div class="loader"></div> <p>正在加载资源,请稍候...</p> </body> </html> `); windowReference.document.close(); // 完成写入,避免资源加载阻塞 } try { AppProductAuthenticationApi.getUrlAccess(apuaId, query).then((res: {urlAccess: string} | undefined | null) => { if (res && res.urlAccess && windowReference) { // 拼接完整地址并跳转 const fullUrl = `${res.urlAccess}${queryString != null ? queryString : ""}`; windowReference.location = fullUrl; } else { // 接口返回异常,关闭窗口 windowReference?.close(); } }).catch(() => { // 捕获接口请求错误,关闭窗口并提示 windowReference?.close(); alert("资源加载失败,请重试"); }); } catch (err) { windowReference?.close(); alert("请求出错,请重试"); }
关键说明:
- 打开窗口后立刻用
document.write()写入加载提示页面,浏览器会直接渲染这个内容,不会显示about:blank - 写入完成后调用
document.close(),确保浏览器结束文档解析,避免后续资源加载被阻塞 - 保留原有的接口逻辑,拿到目标地址后直接修改新窗口的
location属性完成跳转 - 增加了错误捕获逻辑,接口请求失败时关闭窗口并给出提示
注意事项:
- 确保
window.open()是在**用户主动交互(比如点击按钮)**时触发的,否则会被浏览器的弹窗拦截机制阻止 - 如果目标地址是跨域的,跳转后无法再操作新窗口的内容,但这不影响加载提示的显示和跳转逻辑
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

