0

Is it possible to return a value from a Javascript confirm dialog via Selenium JavascriptExecutor ? so the test code can determine if tester clicks OK or Cancel ? I tried this code:

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS);
driver = new ChromeDriver(chromeOptions);
    JavascriptExecutor js = (JavascriptExecutor) driver;

    String result =
        (String)
            js.executeScript(
                "var confirmed = confirm('Press a button Either OK or Cancel'); return confirmed ? 'true' : 'false';");

   WebDriverWait waitForAlert = new WebDriverWait(driver, Duration.ofSeconds(10));
   waitForAlert.until(ExpectedConditions.not(ExpectedConditions.alertIsPresent())); 

   System.out.println("Confirmed: " + result);  // null

Seems like the confirm dialog is running asynchronously so assignment for the return variable happens before the dialog has returned anything.

6
  • when you assign the results of a script to a var like this it should wait for the promise to return. I think it's the "?" in your script that is causing the issue. You should just use "return confirmed;" I think "??" is null coalescer... but is not needed here. It should return true if user chose "OK", otherwise it'll be false. Commented Aug 22, 2024 at 16:57
  • I tried a few variations of that including ?? but the return is always executing immediately: a confirm popup is normally a modal window but apparently not when called by executeScript: looks like the return needs to be wrapped in a promise .
    – timmacp
    Commented Aug 23, 2024 at 10:16
  • I tried using a promise but I don't think that's possible with a standard js confirm popup
    – timmacp
    Commented Aug 23, 2024 at 12:38
  • the driver may not expect you to launch a prompt, so I guess it isn't waiting. Maybe just launch a prompt in your native code there. Commented Aug 23, 2024 at 17:16
  • 1
    No such problem for an injected custom js confirm dialog, so that's the workaround
    – timmacp
    Commented Aug 25, 2024 at 12:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.