Untitled
unknown
plain_text
9 months ago
5.5 kB
13
Indexable
private void handleAccountChooserIfPresent() {
final String original = driver.getWindowHandle();
final int initialCount = driver.getWindowHandles().size();
// 0) Szybki check – czy w ogóle jest okno choosera
Optional<String> chooserBefore = findChooserHandle();
if (chooserBefore.isEmpty()) {
logger.atInfo().log("Account chooser window not open; continue.");
return; // NIC nie zmieniamy, NIC nie zamykamy
}
// 1) Wchodzimy w try/finally – zawsze wróć do original
try {
driver.switchTo().window(chooserBefore.get());
// 2) Czekamy aż chooser będzie gotowy (lista kont widoczna)
if (!waitChooserPopulated(Duration.ofSeconds(10))) {
logger.atInfo().log("Account chooser did not populate in time; skipping click.");
return; // NIE zamykamy, NIE dotykamy innych okien – po prostu wrócimy w finally
}
// 3) Klik preferowane/ pierwsze konto
clickPreferredOrFirstAccount();
} finally {
// 4) ZAWSZE wróć do original, jeśli żyje; jeśli nie – na pierwsze nie-accounts okno
if (!switchToIfExists(original)) {
switchToAnyNonAccountsOrFirst();
}
// 5) Opcjonalnie spróbuj delikatnie zamknąć wyłącznie okno choosera,
// i tylko jeśli wciąż istnieje i mamy >1 okno (żeby nie ubić sesji).
if (driver.getWindowHandles().size() > 1) {
findChooserHandle().ifPresent(h -> closeIfExists(h));
// po zamknięciu upewnij się, że jesteś z powrotem w oryginalnym oknie
switchToIfExists(original);
}
}
logger.atInfo().log("Account chooser handled.");
}
// ========== HELPERY ==========
private Optional<String> findChooserHandle() {
for (String h : driver.getWindowHandles()) {
try {
driver.switchTo().window(h);
String url = safeUrl();
String title = safeTitle();
if ((url.contains("accounts.google.com"))
|| title.toLowerCase().contains("choose an account")) {
return Optional.of(h);
}
} catch (NoSuchWindowException ignore) {}
}
return Optional.empty();
}
private boolean waitChooserPopulated(Duration timeout) {
try {
WebDriverWait w = new WebDriverWait(driver, timeout);
w.until(ExpectedConditions.or(
ExpectedConditions.urlContains("accounts.google.com"),
ExpectedConditions.titleContains("Choose an account")));
w.until(ExpectedConditions.presenceOfElementLocated(accountCard));
return true;
} catch (TimeoutException ignore) {
return false;
}
}
private void clickPreferredOrFirstAccount() {
WebDriverWait w = new WebDriverWait(driver, Duration.ofSeconds(20));
WebElement card;
if (PREFERRED_EMAIL != null) {
card = w.until(d -> d.findElements(accountCard).stream()
.filter(e -> {
String id = Optional.ofNullable(e.getAttribute("data-identifier"))
.orElse(e.getAttribute("data-email"));
return PREFERRED_EMAIL.equalsIgnoreCase(id);
}).findFirst().orElse(null));
if (card == null) {
logger.atInfo().log("Preferred email '%s' not found; clicking first.", PREFERRED_EMAIL);
card = w.until(ExpectedConditions.presenceOfElementLocated(accountCard));
}
} else {
card = w.until(ExpectedConditions.presenceOfElementLocated(accountCard));
}
WebElement clickable;
try {
clickable = card.findElement(By.xpath("ancestor-or-self::*[@role='link'][1]"));
} catch (NoSuchElementException e) {
clickable = card.findElement(accountClickable);
}
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({block:'center'})", clickable);
try {
w.until(ExpectedConditions.elementToBeClickable(clickable));
clickable.click();
} catch (Exception e1) {
try {
new org.openqa.selenium.interactions.Actions(driver)
.moveToElement(clickable).pause(Duration.ofMillis(80)).click().perform();
} catch (Exception e2) {
((JavascriptExecutor) driver).executeScript(
"const el=arguments[0].closest('[role=\"link\"]')||arguments[0]; el.click();", clickable);
}
}
}
private boolean switchToIfExists(String handle) {
if (handle == null) return false;
try {
driver.switchTo().window(handle);
return true;
} catch (NoSuchWindowException e) {
return false;
}
}
private void switchToAnyNonAccountsOrFirst() {
for (String h : driver.getWindowHandles()) {
try {
driver.switchTo().window(h);
if (!safeUrl().contains("accounts.google.com")) return;
} catch (NoSuchWindowException ignore) {}
}
// jeśli wszystkie to accounts (mało prawdopodobne) – przełącz na jakiekolwiek żyjące okno
if (!driver.getWindowHandles().isEmpty()) {
driver.switchTo().window(driver.getWindowHandles().iterator().next());
}
}
private void closeIfExists(String handle) {
try {
if (driver.getWindowHandles().contains(handle) && driver.getWindowHandles().size() > 1) {
driver.switchTo().window(handle);
driver.close();
}
} catch (Exception ignore) {
// nie blokuj testu
}
}
private String safeUrl() {
try { return Optional.ofNullable(driver.getCurrentUrl()).orElse(""); }
catch (Exception e) { return ""; }
}
private String safeTitle() {
try { return Optional.ofNullable(driver.getTitle()).orElse(""); }
catch (Exception e) { return ""; }
}Editor is loading...
Leave a Comment