简体   繁体   English

通过window.open打开窗口,并在加载时使用window.print打印它

[英]Open window by window.open and print it with window.print on load

I have some code like 我有一些像

var windowObject = window.open('','windowObject','arguments...');
windowObject.document.write("<html><body onload="alert(1);window.print();alert(2);"><div>some html</div></body></html>");

The problem is that everything works except the window.print event (on ie, on firefox, it's working). 问题是,除了window.print事件(在firefox上,它正在工作)之外,所有其他东西都可以工作。

Is there a workaround? 有解决方法吗?

Thanks in advance, Gaurav 在此先感谢Gaurav

It's a quotes issue: the double quote after onload= ends the string being written to the document. 这是一个引号问题: onload=之后的双引号结束了写入文档的字符串。 Change the onload quotes to single quotes. 将onload报价更改为单引号。 You also need to add a call to the close() method of the document: 您还需要添加对文档的close()方法的调用:

var windowObject = window.open('','windowObject','arguments...');
windowObject.document.write("<html><body onload='alert(1);window.print();alert(2);'><div>some html</div></body></html>");
windowObject.document.close();

In this line, it appears that you are trying to use nested double quotes: 在此行中,您似乎正在尝试使用嵌套的双引号:

windowObject.document.write("<html><body onload="alert(1);window.print();alert(2);"><div>some html</div></body></html>");

You more likely want to do: 您更可能想做:

windowObject.document.write('<html><body onload="alert(1);window.print();alert(2);"><div>some html</div></body></html>');

Chrome is not allowing us to do print in newly opened window/tab. Chrome浏览器不允许我们在新打开的窗口/标签中进行打印。 You can achieve your requirement by adding a new html file like this <body onload="window.print()"><div>Some html</div></body> and replace your code with var windowObject = window.open('<path_to_your_new_html>','windowObject','arguments...'); 您可以通过添加一个新的HTML文件(例如<body onload="window.print()"><div>Some html</div></body>并将其代码替换为var windowObject = window.open('<path_to_your_new_html>','windowObject','arguments...');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM