Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Classify the “popup” before writing a locator. A Microsoft sign-in interruption may be ordinary page content in the DOM, a new tab or window, or a browser-managed prompt. Selenium Java handles each case differently. Headless Chrome can run the browser with ChromeOptions and --headless=new, but headless mode does not remove Microsoft Entra requirements such as credentials, multifactor authentication (MFA), consent, passwordless verification, or Conditional Access.

First identify which kind of popup you have

Do not start by searching for a universal Microsoft selector. Microsoft sign-in pages and your application’s surrounding markup vary by identity flow, tenant policy, account type, and application. Inspect the state that actually appears in your test.

DOM panel or redirect page

A sign-in form rendered inside the current document is normal web content. Locate the controls in the page under test and wait for an application-specific condition, such as a field becoming visible or a post-login heading appearing. Microsoft’s web flow commonly redirects the browser to the identity platform, then redirects back to the application after authentication and token validation. The exact selectors are application-specific; there is no reliable Microsoft-wide locator to publish.

New tab or browser window

If clicking a link or button opens another browsing context, Selenium exposes it through a different window handle. Save the original handle before the action, wait until the handle set grows, switch to the new handle, and then wait for the state you need.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Browser-managed prompt

HTTP authentication dialogs and other browser prompts are not DOM elements. Use WebDriver’s prompt capabilities and interfaces instead of findElement. The correct action—accept, dismiss, or leave untouched—depends on the prompt type and your test’s purpose.

Start Chrome in headless mode

Selenium’s Chrome setup uses ChromeOptions and passes those options to ChromeDriver. Keep the major versions of Chrome and ChromeDriver aligned, and verify the versions in the CI image rather than assuming a local installation matches it.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
WebDriver driver = new ChromeDriver(options);

try {
    driver.get("https://your-app.example/login");
    // Test-specific interactions go here.
} finally {
    driver.quit();
}

This only starts headless Chrome. It does not make an unattended Microsoft sign-in possible. Tenant policy can still request MFA, passwordless verification, administrator consent, or a device claim. Treat those as authentication design or environment issues, not as missing Selenium waits.

Wait for the state, not an arbitrary delay

Document load completion does not guarantee that a dynamic sign-in panel has rendered. Use an explicit WebDriverWait for the precise condition required by the next test step. Avoid a long Thread.sleep, and do not mix implicit and explicit waits: Selenium warns that combined timing models can produce unpredictable delays.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
wait.until(ExpectedConditions.visibilityOfElementLocated(
    By.cssSelector("your-app-specific-selector")));

Replace the CSS selector with one taken from your application’s DOM. Before adding it to a test, confirm that it identifies the intended control in the actual tenant and sign-in variant used by the test.

Handle a sign-in tab or window

Window handles are opaque identifiers. Compare the set before and after the action, wait for a second handle, switch to it, and wait for its expected page state. This pattern also works when the application opens a tab instead of a separate OS window.

import java.time.Duration;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

String original = driver.getWindowHandle();
Set<String> before = driver.getWindowHandles();

// Trigger the application action that may open Microsoft sign-in.
driver.findElement(By.id("sign-in" )).click();

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
wait.until(d -> d.getWindowHandles().size() > before.size());

String loginHandle = driver.getWindowHandles().stream()
    .filter(handle -> !before.contains(handle))
    .findFirst()
    .orElseThrow(() -> new IllegalStateException("No new sign-in window"));

driver.switchTo().window(loginHandle);
wait.until(ExpectedConditions.titleContains("Sign"));

// Interact with selectors observed in this application’s sign-in page.
// Return to the original context when the flow is complete.
driver.switchTo().window(original);

Do not rely only on a title: titles can vary by locale and flow. A stable, application-observed element or URL state is usually a better readiness condition.

Handle browser prompts correctly

A browser prompt cannot be selected with CSS or XPath. Configure unhandled-prompt behavior when appropriate, and use WebDriver’s alert interface for JavaScript dialogs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import org.openqa.selenium.Alert;

Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
alert.accept();                 // or alert.dismiss()

HTTP authentication and other browser-level dialogs may require capabilities or a Chrome-specific setup. Decide whether the test should accept, reject, or report the prompt; silently dismissing it can hide a real authentication failure.

Microsoft identity requirements that headless mode cannot bypass

Microsoft Entra ID delegates authentication to the identity platform. Depending on the tenant and account, the flow can require a password, MFA, passwordless verification, user or administrator consent, or Conditional Access evaluation. On success, the identity platform returns a token and the application establishes its sign-in session.

When MFA, consent, or Conditional Access appears

Capture the URL, page state, and diagnostic screenshot at the point where the flow stops, then record the Chrome, ChromeDriver, Selenium, Java, operating-system, account, tenant, and policy details. Ask the identity administrator which test-tenant policy is expected. A timeout while waiting for a username field is not equivalent to a policy that is deliberately asking for a phone approval.

ROPC is a constrained test option

Microsoft’s automated-testing guidance discusses Resource Owner Password Credential (ROPC) for particular controlled scenarios. ROPC does not support MFA, and its suitability depends on tenant policy and security approval. It is not a general workaround for a production website’s interactive login and should never be presented as a way to defeat an organization’s controls.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Device code for a genuinely browserless client

For an application that needs Microsoft API tokens without hosting a browser, MSAL Java supports device-code flow. The program displays a code; the user completes normal authentication on another device, including required consent or MFA. This changes the application’s authentication design. It does not test the website’s Microsoft login UI in Chrome and therefore cannot replace a Selenium UI test whose purpose is to verify redirects, fields, or browser behavior.

A diagnostic sequence that avoids flaky fixes

  1. Where policy permits, run one diagnostic attempt with a visible browser and save the URL, screenshot, and visible page state at the stall.
  2. Classify the interruption as DOM content, a new tab/window, or a browser-managed prompt.
  3. For DOM content, inspect the current document and wait explicitly for an app-specific condition. Do not assume undocumented Microsoft selectors.
  4. For a new context, compare handle sets, wait for the new handle, switch to it, and wait for its expected state.
  5. For a browser prompt, use the prompt interface or configured behavior appropriate to that prompt type.
  6. If the page requests MFA, consent, passwordless verification, or Conditional Access, stop tuning popup selectors. Use an approved test account and tenant design, or choose device-code flow when the product is truly a browserless API client.
  7. Keep the environment record with the test result so a version mismatch can be separated from an identity-policy decision.

Common failures and fixes

“No such element” on a Microsoft control

Cause: the control is in another window, has not rendered, or the flow redirected to a different page variant. Fix: log the current URL and handles, switch context if necessary, and replace an immediate lookup with an explicit wait for a selector verified in that tenant.

Timeout waiting for a username or password field

Cause: the tenant presented MFA, passwordless verification, consent, a device challenge, or an error page instead. Fix: capture the visible state and involve the identity administrator; do not increase the timeout indefinitely.

Test passes visibly but fails headless

Cause: timing, viewport-dependent layout, device or Conditional Access policy, or a browser/driver mismatch. Fix: compare browser and driver major versions, set a deliberate window size if the application depends on responsive layout, use explicit waits, and inspect the same URL and policy result in both modes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The script waits forever after clicking sign-in

Cause: the application reused the current tab or opened a handle that your code did not identify. Fix: capture handles before the click, wait for the expected change, and handle both same-tab and new-tab outcomes in the test’s state machine.

Prompt handling closes the wrong dialog

Cause: a JavaScript alert was confused with a browser-managed authentication prompt. Fix: identify the prompt class first; use switchTo().alert() only for WebDriver-supported web dialogs and configure browser behavior for browser-level prompts.

Performance, reliability, and test boundaries

Explicit waits improve reliability by polling for the condition that matters, but they cannot make an unavailable identity service or an unmet tenant policy succeed. Keep waits local to each transition instead of one oversized global timeout. Reuse a driver only when your test isolation model safely clears cookies and session state; otherwise, a fresh profile prevents one account’s SSO state from masking another test’s behavior.

For repeatable integration tests, use a tenant-approved test account and document whether interactive MFA is expected. If the requirement is to verify the browser UI, retain Selenium. If the requirement is only to obtain tokens and call APIs, evaluate MSAL Java device code instead. Those are different tests with different success criteria.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean image or PDF of a page rather than exercising Microsoft’s login UI, ScreenshotNeo provides a single HTTP call. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for the complete option set, including full-page and selector capture, device presets, viewport and retina settings, PDF paper and margin controls, custom CSS or JavaScript, clicks, selector waits, network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and the OpenAPI specification. Parameter names used by other screenshot APIs are accepted to ease migration.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free, and every feature is included on every plan. Create a free ScreenshotNeo account to try it.

Frequently Asked Questions

Can Selenium click a Microsoft MFA approval automatically?

Not reliably or appropriately. MFA and passwordless steps are controlled by tenant policy and may require a user or approved test design; diagnose the state and use an authorized account and flow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use a fixed sleep after opening the login page?

No. Wait for the specific element, handle, title, URL, or prompt state required by the next action, and avoid mixing implicit and explicit waits.

Is device-code authentication a replacement for Selenium?

Only when the application needs browserless Microsoft API access. It does not exercise a website’s interactive login page, redirects, or browser UI.

The Bottom Line

Handle the interruption according to its type—DOM content, new window, or browser prompt—then wait for the exact state your application requires. Headless Chrome changes presentation, not Microsoft Entra policy; MFA, consent, and Conditional Access must be addressed through an approved test design.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.