Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

java - How can I tell Selenium to press cancel on a print popup?

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;

     }  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...