Categories
JavaScript Answers

How to close window automatically after printing dialog closes with JavaScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.