print dialog does not let next code to be executed in selenium

The code that i'm using is below. First line clicks on 'PrintButton" which opens up "Print" dialog. Once this is open, I expect a console output "Sending Esc key - Start" and then subsequently one of the action like robot, actions, alert dismiss, window switch to happen (based on whichever code is uncommented). But instead, the console does not print anything UNLESS i click on Cancel in print dialog. So, once i click on cancel, the sysout prints the message, performs the action (and nothing useful happens because of those actions) and then prints another console msg.

My Question is two parts. a. Why is the compiler (or program) not moving to next line? b. How can I handle this print dialog? (read all the articles in internet, tried the suggested methods but nothing worked).

driver.findElement(By.id("PrintButton")).click();
System.out.println("Sending Esc key - Start");
/*Robot r = new Robot();
r.delay(10000);
r.keyPress(KeyEvent.VK_ESCAPE);
r.keyPress(KeyEvent.VK_ESCAPE);
r.keyPress(KeyEvent.VK_ESCAPE);
*/
/*Actions a = new Actions(driver).sendKeys(Keys.CANCEL);*/
/*driver.switchTo().alert().dismiss();*/
/*List<String> handles = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(handles.get(handles.size()-1));*/
System.out.println("Sending Esc key - done");

Upvotes: 1

Views: 2326

Answers (2)

Rufat N
Rufat N

Reputation: 21

I had the same problem on ChromeDriver and found the only way is to click the print button with JavascriptExecutor in a async fashion.

WebElelement print_button = driver.findElement(By.id("PrintButton"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("var elem=arguments[0]; setTimeout(function() {elem.click();}, 100)", print_button);

Inspired by this tread

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328624

The driver never returns because Selenium uses JavaScript internally to "click" the button. Clicking the button opens a modal dialog which blocks the browser's JavaScript engine (all animations stop as well). This is partly because of the modal dialog (alert() does the same thing) but also because you probably want to print the page as it is - it shouldn't change while you print it.

Workaround: Make sure the element has the focus (using Selenium). Then use Robot to drive the whole process: Send a key press to activate the button (it's very hard to locate the button on the screen). Then the print dialog should show up and it should have the focus. The next key presses in Robot should then drive the dialog.

Note: This is brittle. My suggestion is not to test the print dialog this way. If you need this, then Java+Selenium might not be the correct solution. Look at professional UI testing tools like QF-Test.

Related:

Upvotes: 0

Related Questions