6

I am checking whether or not a page appears using Selenium. When I click the page, however, a printer print prompt appears (like the window that says select printer and such). How can I have Selenium close this window by hitting cancel?

I tried looking to alerts, but it seems like those will not work since the print window is a system prompt. It does not recognize any alerts appearing.

The most recent I tried using is by just sending keys like tab and enter in order to have the cancel button selected, however, it doesn't recognize any keys as being pressed.

How can I handle this case?

public static boolean printButton() throws Exception {

    WebDriver driver = new FirefoxDriver();
    driver.get("website");


    try {

        Thread.sleep(3000);
        WebElement temp = driver.findElement(By.xpath("//*[@id='block-print-ui-print-links']/div/span/a"));
        temp.click();
        Actions action = new Actions(driver); 
        action.sendKeys(Keys.TAB).sendKeys(Keys.ENTER);

        Thread.sleep(6000);

     }

     catch (Exception e) {

        System.out.println("No button.");
        driver.close();
        return false;

     }  
Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
J. Doe
  • 1,479
  • 5
  • 25
  • 49

7 Answers7

11

I would simply disable the print dialog by overriding the print method :

((JavascriptExecutor)driver).executeScript("window.print=function(){};");

But if you goal is to test that the printing is called then :

// get the print button
WebElement print_button = driver.findElement(By.cssSelector("..."));

// click on the print button and wait for print to be called
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
((JavascriptExecutor)driver).executeAsyncScript(
    "var callback = arguments[1];" +
    "window.print = function(){callback();};" +
    "arguments[0].click();"
    , print_button);
Florent B.
  • 41,537
  • 7
  • 86
  • 101
  • 1
    I selected this answer over the other one because this one does not require me to download any extra tools. Thanks to both of you – J. Doe Apr 15 '16 at 12:34
  • Hi @florent-b, Can you please help me for following problem : https://stackoverflow.com/questions/47885424/close-print-preview-window-from-google-chrome-extension-project-using-jquery – Manish Sapkal Jan 01 '18 at 08:10
8

If you are going for testing only Chrome browser here is mine solution. Because of 'Robot' class or disabling print didn't work for my case.

// Choosing the second window which is the print dialog.
// Switching to opened window of print dialog.
driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());

// Runs javascript code for cancelling print operation.
// This code only executes for Chrome browsers.
JavascriptExecutor executor = (JavascriptExecutor) driver.getWebDriver();
executor.executeScript("document.getElementsByClassName('cancel')[0].click();");

// Switches to main window after print dialog operation.
driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());

Edit: In Chrome 71 this doesn't seem to work anymore since the script can't find the Cancel button. I could make it work by changing the line to:

executor.executeScript("document.querySelector(\"print-preview-app\").shadowRoot.querySelector(\"print-preview-header\").shadowRoot.querySelector(\"paper-button.cancel-button\").click();");
Erçin Akçay
  • 1,383
  • 4
  • 18
  • 34
  • 1
    This doesn't work for me in python: browser.execute_script("document.querySelector(\"print-preview-app\").shadowRoot.querySelector(\"print-preview-header\").shadowRoot.querySelector(\"paper-button.cancel-button\").click();") I am getting an error: JavascriptException("javascript error: Cannot read property 'shadowRoot' of null\n (Session info: chrome=75.0.3770.142)\n (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)", None, None) JavascriptException – MacMarde Jul 19 '19 at 20:13
  • 1
    @MacMarde check solution for chrome 75 here https://stackoverflow.com/a/57218421/5324105 – Rahul L Jul 27 '19 at 05:41
  • 2
    In chrome 79, this is the locator for the cancel button in the print dialog: return document.querySelector('print-preview-app').shadowRoot.querySelector('print-preview-sidebar').shadowRoot.querySelector('print-preview-button-strip').shadowRoot.querySelector('cr-button.cancel-button') – JackhammersForWeeks Nov 15 '19 at 23:24
4

Actually you can't handle windows (OS) dialogs inside Selenium WebDriver. This what the selenium team answers here

The current team position is that the print dialog is out of scope for the project. WebDriver/Selenium is focused on emulating a user's interaction with the rendered content of a web page. Other aspects of the browser including, but not limited to print dialogs, save dialogs, and browser chrome, are all out of scope.

You can try different approach like AutoIt

Community
  • 1
  • 1
Eugene
  • 1,865
  • 3
  • 21
  • 24
3

we can also use key for handling the print or press the cancel button operation. and it works for me.

driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());
WebElement webElement = driver.findElement(By.tagName("body"));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());
akanshu
  • 41
  • 3
1

Native window based dialog can be handled by AutoItX as described in the following code

File file = new File("lib", jacobDllVersionToUse);
System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath());
WebDriver driver = new FirefoxDriver();
driver.get("http://www.joecolantonio.com/SeleniumTestPage.html");
WebElement printButton = driver.findElement(By.id("printButton"));
printButton.click();
AutoItX x = new AutoItX();
x.winActivate("Print");
x.winWaitActive("Print");
x.controlClick("Print", "", "1058");
x.ControlSetText("Print", "", "1153", "50");
Thread.sleep(3000); //This was added just so you could see that the values did change.
x.controlClick("Print", "", "2");

Reference : http://www.joecolantonio.com/2014/07/21/selenium-how-to-handle-windows-based-dialogs-and-pop-ups/

Raghu K Nair
  • 3,854
  • 1
  • 28
  • 45
0

Sometimes 2 different statements as above (webElement.sendKeys(Keys.TAB) webElement.sendKeys(Keys.ENTER)) will not work, you can use with combination of Tab and Enter keys as below, This will close the Print preview window.

Using C# :

Driver.SwitchTo().Window(Driver.WindowHandles[1]);
IWebElement element = Driver.FindElement(By.TagName("body"));  
element.SendKeys(Keys.Tab + Keys.Enter);                
Driver.SwitchTo().Window(Driver.WindowHandles[0]);
0

Erçin Akçay answer updated.

// Choosing the second window which is the print dialog.
            // Switching to opened window of print dialog.
            driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());

            // Runs javascript code for cancelling print operation.
            // This code only executes for Chrome browsers.
            JavascriptExecutor js = (JavascriptExecutor)driver;
        
            js.executeScript("document.querySelector(\"body > print-preview-app\").shadowRoot.querySelector(\"#sidebar\").shadowRoot.querySelector(\"print-preview-button-strip\").shadowRoot.querySelector(\"div > cr-button.cancel-button\").click();");

            // Switches to main window after print dialog operation.
            driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());