Sometimes, we want to close window automatically after printing dialog closes with JavaScript.
In this article, we’ll look at how to close window automatically after printing dialog closes with JavaScript.
How to close window automatically after printing dialog closes with JavaScript?
To close window automatically after printing dialog closes with JavaScript, we call window.close
when we move focus back onto the main window after printing.
For instance, we write
setTimeout(() => {
window.print();
}, 500);
window.onfocus = () => {
setTimeout(() => {
window.close();
}, 500);
};
to call window.print
to open the browser print dialog.
Then we set window.onfocus
to a function that runs when the window gets focus.
In it, we call window.close
to close the window after a 500 ms delay in the setTimeout
callback.
Conclusion
To close window automatically after printing dialog closes with JavaScript, we call window.close
when we move focus back onto the main window after printing.