Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.print(); does not work in Safari

The print method does not work on window when using an onclick link Safari. What is the alternative to have a webpage print, in safari via onclick code that is placed on a button? Another odd behavior that's occurring is that when I try and close the window, the print dialog native to the browser then appears.

like image 829
fauverism Avatar asked Jul 01 '15 20:07

fauverism


People also ask

How do I allow Safari to Print?

In the Safari app on your Mac, choose File > Print. Click the options pop-up menu (in the separator bar), choose Safari, then set the webpage printing options.


2 Answers

Try this solution:

try {
  // Print for Safari browser
  document.execCommand('print', false, null)
} catch {
  window.print()
}
like image 59
Alex Golovin Avatar answered Sep 17 '22 14:09

Alex Golovin


I was facing a similar issue with the Safari browser (and not any others). In my case, aborting all API calls currently in progress immidiately showed the native print dialog.

I'm guessing the reason why your dialog showed up when trying to close the tab/page is that all the network requests are cancelled then.

Here's an example of how to create a pool of ajax requests (when using jQuery): Stop all active ajax requests in jQuery

Also, to make it work consistently, I had to wrap the $.xhrPool.abortAll function in a short timeout (100ms).

My click handler function (simplified) looks something like this:

function myFunction() {
    window.print();
    window.setTimeout(function () {
        $.xhrPool.abortAll()
    }, 100);
}
like image 29
ReGdYN Avatar answered Sep 17 '22 14:09

ReGdYN