简体   繁体   中英

How to handle alert box that appears while page is loading, using selenium java

I am trying to automate a ServiceNow webpage by automatically accepting tasks.

Sequence of events:
1. Right on a record and hit 'Accept Task'
2. An alert box shows up asking for my confirmation, I hit the 'Ok' button.
3. The page starts refreshing and now a 2nd alert box shows up stating the task has been accepted.

What I have tried:

  • I could get past steps 1 and 2 using driver.switchTo().alert.accept() , but doing same thing on step 3 throws org.openqa.selenium.UnhandledAlertException: unexpected alert open
  • Using thread.sleep() didn't help
  • Using driver.switchTo().defaultcontent() didn't help as well
  • I can override and close the alert using JavaScript Executor but that's not what I want because I need the alert text as well ( https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/27 )
     // this does the trick of overriding and closing the 2nd alert box, but I need the alert text as well and hence need a better solution```

What I have written:

//handling Alert #1
if(driver.switchTo().alert().getText().equalsIgnoreCase("Are you sure you want to accept this task?"))
    {
        driver.switchTo().alert().accept(); //successfully handled Alert #1
        System.out.println("accepted");
    }

Thread.sleep(3000);
driver.switchTo().defaultContent();

//Handling Alert #2
if(driver.switchTo().alert().getText().endsWith("has been accepted"))
    {
        System.out.println(driver.switchTo().alert().getText());
        driver.switchTo().alert().accept(); //failed to handle Alert #2
    }

Possible cause of the issue: The 2nd alert box appears when the page is loading.

Hope I have made myself clear this time. Please help how to get the text of the 2nd alert box and close it, because the text decides the logic of the later part.

Alert alert = driver.switchTo().alert();
    alert.getText();

you can use this method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM