Capture screenshot of alert

12,476

Solution 1

You can always get the screenshot of entire page using Robot. I just tried it out, this code is working:

WebDriver driver;
@Before
public void init() throws Exception {
    driver = new FirefoxDriver();
    driver.get("http://www.tizag.com/javascriptT/javascriptalert.php");
}

@Test
public void bla() throws AWTException, IOException {
    WebElement element = driver.findElement(By.xpath("//input[@type=\"button\"]"));
    // Trigger the alert
    element.click();
    BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    ImageIO.write(image, "png", new File("c:\\localdev\\bla.png"));
    driver.switchTo().alert().accept();
}

Solution 2

You have to handle the alert before you take a screenshot... you can read about it more here https://code.google.com/p/selenium/issues/detail?id=4412

Share:
12,476

Related videos on Youtube

Dinu
Author by

Dinu

Updated on June 04, 2022

Comments

  • Dinu
    Dinu almost 2 years

    I have used the below code to take screenshot of the application after pop up appears.

    Alert alert = driver.switchTo().alert();
    File scrFile= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("G:\\Screens\\sc1.jpg"));
    String alertMsg = alert.getText();
    System.out.println(alertMsg);
    alert.accept();
    

    But it is throwing this exception

    Exception in thread "main" org.openqa.selenium.UnhandledAlertException:Modal dialog present: Assessment Name already Exist.

    But the code works fine if I remove the screenshot procedures.

    • Dinu
      Dinu over 9 years
      Hey Nick the link you have given as duplicate is also the same link as that of my question. Only one question exists
    • Nick Grealy
      Nick Grealy over 9 years
      I'm an idiot. Thank you!
    • Nick Grealy
      Nick Grealy almost 7 years
      Thanks @AndersLindén
  • Dinu
    Dinu about 10 years
    So it it no possible to take screenshot of the alert
  • Dinu
    Dinu about 10 years
    But the problem with this method is that if we are performing the test in background then the actual screen which is active will be captured.
  • Pavel Niedoba
    Pavel Niedoba over 7 years
    I run selenium on Linux with virtual display and it works for me