开发者

How can I open, and print the contents of, a browser window using JavaScript without showing the browser window?

I am using the following JavaScript code to print a <div>. I have called the printit() function on a button click. When the function runs, I am getting two windows. One is showing printing options, and in the background there is a preview window which is showing data from the <div> created by the function.

I want to exclude that background window. How can I do it?

<script>
function printit() 
{
    var DocumentContainer = document.getElementById('printthis');
    var WindowObject = window.open('', 'PrintWindow', 'width=750,height=650,top=50,lef开发者_StackOverflow中文版t=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}
</script>


Instead of creating a window, which cannot be hidden, you can create a hidden iframe, write a document into it, and call the print function on its window object, if you want.


You can't do that with the current approach. That is the window that you create in the function. If you don't have that window, you don't have anything to print.

Another approach would be to use a media CSS. You can have a CSS for print that hides everything that you don't want included in the printout. That way you can print the current window instead of creating a new window.


You can’t. When you create a new browser window using JavaScript, there’s no way to make it invisible. (You can imagine why: I visit a random website on the internet, and it creates an invisible browser window on my computer? No thanks!)

I suggest you just be happy having the window showing. Why shouldn’t the user see what’s being printed?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜