|
3 | 3 |
|
4 | 4 | using OpenQA.Selenium; |
5 | 5 | using OpenQA.Selenium.Support.UI; |
6 | | -using System; |
7 | 6 |
|
8 | 7 | namespace Microsoft.AspNetCore.Components.E2ETest; |
9 | 8 |
|
10 | 9 | internal static class WebDriverExtensions |
11 | 10 | { |
12 | | - private static string GetFindPositionScript(string elementId) => |
13 | | - $"return Math.round(document.getElementById('{elementId}').getBoundingClientRect().top + window.scrollY);"; |
14 | | - |
15 | 11 | public static void Navigate(this IWebDriver browser, Uri baseUri, string relativeUrl) |
16 | 12 | { |
17 | 13 | var absoluteUrl = new Uri(baseUri, relativeUrl); |
@@ -45,32 +41,33 @@ public static void WaitForElementToBeVisible(this IWebDriver browser, By by, int |
45 | 41 |
|
46 | 42 | public static long GetElementPositionWithRetry(this IWebDriver browser, string elementId, int retryCount = 3, int delayBetweenRetriesMs = 100) |
47 | 43 | { |
48 | | - var jsExecutor = (IJavaScriptExecutor)browser; |
49 | | - string script = GetFindPositionScript(elementId); |
50 | | - browser.WaitForElementToBeVisible(By.Id(elementId)); |
51 | 44 | string log = ""; |
52 | 45 |
|
53 | 46 | for (int i = 0; i < retryCount; i++) |
54 | 47 | { |
55 | 48 | try |
56 | 49 | { |
57 | | - var result = jsExecutor.ExecuteScript(script); |
58 | | - if (result != null) |
59 | | - { |
60 | | - return (long)result; |
61 | | - } |
| 50 | + browser.WaitForElementToBeVisible(By.Id(elementId)); |
| 51 | + var element = browser.FindElement(By.Id(elementId)); |
| 52 | + var elementLocation = element.Location.Y; |
| 53 | + |
| 54 | + // Get scroll position using JavaScript (this is less likely to fail than element positioning) |
| 55 | + var jsExecutor = (IJavaScriptExecutor)browser; |
| 56 | + var scrollY = (long)jsExecutor.ExecuteScript("return window.scrollY"); |
62 | 57 |
|
63 | | - log += $"Attempt {i + 1}: Script returned null. "; |
| 58 | + return elementLocation + scrollY; |
64 | 59 | } |
65 | | - catch (OpenQA.Selenium.JavaScriptException ex) |
| 60 | + catch (Exception ex) |
66 | 61 | { |
67 | | - // JavaScript execution failed, retry |
68 | | - log += $"Attempt {i + 1}: JavaScriptException - {ex.Message}. "; |
| 62 | + log += $"Attempt {i + 1}: - {ex.Message}. "; |
69 | 63 | } |
70 | 64 |
|
71 | | - Thread.Sleep(delayBetweenRetriesMs); |
| 65 | + if (i < retryCount - 1) |
| 66 | + { |
| 67 | + Thread.Sleep(delayBetweenRetriesMs); |
| 68 | + } |
72 | 69 | } |
73 | 70 |
|
74 | | - throw new Exception($"Failed to execute script to get position for element '{elementId}' after {retryCount} retries. Debug log: {log}"); |
| 71 | + throw new Exception($"Failed to get position for element '{elementId}' after {retryCount} retries. Debug log: {log}"); |
75 | 72 | } |
76 | 73 | } |
0 commit comments