0

I trying to practice handling Javascript alert. I want to accept alert ,which comes out of iframe in w3school website.

    WebDriver driver = new ChromeDriver();
    driver.get("http://www.w3schools.com/js/tryit.asp?filename=tryjs_alert");
    driver.switchTo().frame("iframeResult");

    driver.findElement(By.xpath("/html/body/button")).click();
    WebElement editable = driver.switchTo().activeElement(); 
    editable.sendKeys("enter");         

    //handle pop alert
    String mainPage = driver.getWindowHandle();
    Alert alt = driver.switchTo().alert();
    alt.accept();
    driver.switchTo().window(mainPage);

I am just getting alert box and then below error. I am not able to accept it. Exception in thread "main" org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : I am an alert box!}

1 Answer 1

1

You have all the right code. The error comes when you try to do something other than handle the alert once the alert is up. You have some extraneous code that isn't needed to handle the alert. I've removed it in the code below. You can add things back but you will need to add them before or after launching the alert and handling it.

WebDriver driver = new ChromeDriver();
driver.get("http://www.w3schools.com/js/tryit.asp?filename=tryjs_alert");
driver.switchTo().frame("iframeResult");

driver.findElement(By.xpath("/html/body/button")).click(); // this launches the alert
driver.switchTo().alert().accept(); // this one line accepts the alert
driver.switchTo().defaultContent(); // you will probably need to switch back out of the IFRAME at some point to access the main page again so I added this line

One thing that I would strongly suggest for you is to read some guides on debugging in the IDE of your choice. If you learned how to debug your code, you could walk through it and more likely see where the issue was and fix it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.