Window.print()在window.location.replace之前运行

时间:2017-06-28 21:52:48

标签: javascript

我当前的代码正在尝试重定向到具有更多可打印版本信息的页面,我使用window.location.replace将页面替换为打印友好页面,然后使用window.print()将其打印出来但是,它会在替换页面并尝试打印上一页之前提供打印提示。有关为何发生这种情况的任何建议吗?

function btnIncidentPrint(id)
{
window.location.replace('<c:url value="/print/?objtype=INCIDENT&type=INCIDENT&id="/>'+id);
window.print();
}

1 个答案:

答案 0 :(得分:2)

浏览器可能无法立即响应window.location更改;可能会有延迟。

但是,一旦window.location更改做出响应,它将不再运行您的任何代码,因此您将无法再window.print()

一种解决方案是将打印友好视图放在另一个窗口或框架中,然后在该窗口而不是您要替换的窗口上调用.print()。你可以立即删除框架,这样就不会使页面混乱。

var iframe = document.createElement('iframe');
iframe.onload = function() {
  iframe.contentWindow.print();
  iframe.parentNode.removeChild(iframe);
};
iframe.src = '?view=print';
document.body.appendChild(iframe);
相关问题