I have to handle print dialog (the same one that appears when clicking ctrl-p in browser). I tried with:
Alert printDialog = driver.switchTo().alert();
printDialog.dismiss();
but it didn't work. Also I couldn't catch its window handle, because it's not a window...
Is it possible to handle these objects and how?
When Selenium opened up the print dialog window, it became stuck waiting around, but the delayed click was still running and waiting to click after 4 seconds of selenium opening the print window. Then the click would execute, and selenium retook control because the print window was taken care of.
Unfortunately, WebDriver can't handle these (or any other browser or OS dialog). Moreover, they tend to look differently across browsers / systems / language settings, so there's probably no definite answer. You'll need to detect and handle every possible case in order to make it work everywhere. Your options include:
The Robot
class, it allows you to "press" programatically anything on the keyboard (or clicking blindly) and therefore getting rid of the dialog by, say, pressing Enter or Esc. However, as told above, any advanced interaction is dependant on OS / language / printer.
// press Escape programatically - the print dialog must have focus, obviously
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ESCAPE);
r.keyRelease(KeyEvent.VK_ESCAPE);
AutoIt. It's a Windows program useful for handling any system-level automation. Same dependancy as above.
That's more or less it. If you can avoid the print dialog, try to take screenshot of the page and print it using standard Java tools.
One CAN handle Print dialog with Selenium in Chrome. Not sure about other browsers.
Access to Print dialog was added in ChromeDriver-2.17. Details can be found here: https://bugs.chromium.org/p/chromedriver/issues/detail?id=1087
Right-click on Print dialog -> Inspect Element. As a result, the DOM of Print dialog will open in a separate window. Now you can produce locators for any element on the dialog and use them in your tests.
To close the Print dialog one can do the following:
//Switch to Print dialog
Set<String> windowHandles = driver.getWindowHandles();
if (!windowHandles.isEmpty()) {
driver.switchTo().window((String) windowHandles.toArray()[windowHandles.size() - 1]);
}
//Now work with the dialog as with an ordinary page:
driver.findElement(By.className("cancel")).click();
I was able to resolve this issue by adding --kiosk-printing
which bypasses the print dialog completely. I have my default print set to pdf, so I end up with a pdf in my Downloads folder, but at least selenium doesn't hang. Here's what the code looks like:
ChromeOptions cOptions = new ChromeOptions();
cOptions.addArguments("kiosk-printing");
RemoteWebDriver driver = new RemoteWebDriver(hostUrl, cOptions);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With