在重定向到新 URL 之前获取 URL

问题描述 投票:0回答:1

我正在编写此脚本,需要从浏览器检索 URL。 测试用例是,我首先登录网站并单击一个按钮,单击按钮后,它会自动打开一个新页面。在这个新页面中,它最初有一个 URL,并立即重定向到一个新 URL。然而,这个过程发生得太快了。因此,我可以使用以下代码检索第一个生成的 URL,

driver.getCurrentUrl();

如何减慢重定向过程以便检索原始 URL?

我这样做是因为,验证原始 URL 是测试要求的一部分。

提前致谢。

java selenium-webdriver url
1个回答
0
投票

我假设新的 URL 在新窗口中打开

尝试像这样注入 JavaScript 来拦截并暂停重定向。您可以在测试中执行 JavaScript 来临时覆盖 window.location 行为,然后切换到新窗口

注意: 单击按钮之前执行 Javascript

// Inject JavaScript to override window.location
((JavascriptExecutor) driver).executeScript("window.location.replace = function(url) { setTimeout(() => { window.location.href = url; }, 5000); }");

完整的代码是这样的

// Inject JavaScript to delay the redirection
((JavascriptExecutor) driver).executeScript(
    "window.location.replace = function(url) { setTimeout(() => { window.location.href = url; }, 2000); }"
);

// Click the button that triggers the redirection
WebElement redirectButton = driver.findElement(By.id("redirect-button"));
redirectButton.click();

// Wait until the URL contains "code"
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.urlContains("code"));

// Capture the current URL once the condition is met
String currentUrl = driver.getCurrentUrl();
System.out.println("Current URL containing 'code': " + currentUrl);
© www.soinside.com 2019 - 2024. All rights reserved.