From d701cee65546b9bb9d09d92bb927835dbaff5580 Mon Sep 17 00:00:00 2001 From: Alex Maitland Date: Mon, 30 May 2022 12:00:18 +1000 Subject: [PATCH] Enhancement - Add WaitForSelectorAsync extension method. (#4095) * Enhancement - Add WaitForSelectorAsync extension method. string script = "const newDiv = document.createElement('div'); newDiv.id = 'myElement'; document.body.append(newDiv);"; await Task.WhenAll( browser.WaitForSelectorAsync("#myElement");, chromiumWebBrowser.EvaluateScriptAsync(script)); Resolves #4094 --- .../Selector/WaitForSelectorAsyncTests.cs | 204 ++++++++++++++++++ CefSharp/JavascriptResponse.cs | 2 + CefSharp/WaitForSelectorAsyncResponse.cs | 49 +++++ CefSharp/WebBrowserExtensions.cs | 125 ++++++++++- 4 files changed, 379 insertions(+), 1 deletion(-) create mode 100644 CefSharp.Test/Selector/WaitForSelectorAsyncTests.cs create mode 100644 CefSharp/WaitForSelectorAsyncResponse.cs diff --git a/CefSharp.Test/Selector/WaitForSelectorAsyncTests.cs b/CefSharp.Test/Selector/WaitForSelectorAsyncTests.cs new file mode 100644 index 000000000..e06ef8ddb --- /dev/null +++ b/CefSharp.Test/Selector/WaitForSelectorAsyncTests.cs @@ -0,0 +1,204 @@ +using Xunit.Abstractions; +using Xunit; +using System.Threading.Tasks; +using CefSharp.OffScreen; +using CefSharp.Example; +using System; +using CefSharp.Web; + +namespace CefSharp.Test.Selector +{ + //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle + [Collection(CefSharpFixtureCollection.Key)] + public class WaitForSelectorAsyncTests + { + + private readonly ITestOutputHelper output; + private readonly CefSharpFixture fixture; + + public WaitForSelectorAsyncTests(ITestOutputHelper output, CefSharpFixture fixture) + { + this.fixture = fixture; + this.output = output; + } + + [Fact] + public async Task CanWork() + { + const string elementId = "newElement"; + + using (var browser = new ChromiumWebBrowser(CefExample.DefaultUrl)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var selectorTask = browser.WaitForSelectorAsync($"#{elementId}"); + var evaluateTask = browser.EvaluateScriptAsync("const newDiv = document.createElement('div'); newDiv.id = 'newElement'; const newContent = document.createTextNode('Hi there and greetings!'); newDiv.appendChild(newContent); document.body.append(newDiv);"); + + await Task.WhenAll(selectorTask, evaluateTask); + + var selectorResponse = selectorTask.Result; + var evalauteResponse = evaluateTask.Result; + + Assert.True(selectorResponse.Success); + Assert.True(evalauteResponse.Success); + + Assert.Equal(elementId, selectorResponse.ElementId); + Assert.Equal("DIV", selectorResponse.TagName); + } + } + + [Fact] + public async Task CanWorkForDelayedAction() + { + const string elementId = "newElement"; + + using (var browser = new ChromiumWebBrowser(CefExample.DefaultUrl)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var selectorTask = browser.WaitForSelectorAsync($"#{elementId}"); + var evaluateTask = Task.Run(async () => + { + await Task.Delay(500); + return await browser.EvaluateScriptAsync("const newDiv = document.createElement('div'); newDiv.id = 'newElement'; const newContent = document.createTextNode('Hi there and greetings!'); newDiv.appendChild(newContent); document.body.append(newDiv);"); + }); + + await Task.WhenAll(selectorTask, evaluateTask); + + var selectorResponse = selectorTask.Result; + var evalauteResponse = evaluateTask.Result; + + Assert.True(selectorResponse.Success); + Assert.True(evalauteResponse.Success); + + Assert.True(selectorResponse.ElementAdded); + Assert.Equal(elementId, selectorResponse.ElementId); + Assert.Equal("DIV", selectorResponse.TagName); + } + } + + [Fact] + public async Task CanWorkForRemoved() + { + const string elementId = "content"; + + using (var browser = new ChromiumWebBrowser(CefExample.DefaultUrl)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var selectorTask = browser.WaitForSelectorAsync($"#{elementId}", removed:true); + var evaluateTask = browser.EvaluateScriptAsync($"document.querySelector('#{elementId}').remove();"); + + await Task.WhenAll(selectorTask, evaluateTask); + + var selectorResponse = selectorTask.Result; + var evalauteResponse = evaluateTask.Result; + + Assert.True(selectorResponse.Success); + Assert.True(evalauteResponse.Success); + + Assert.False(selectorResponse.ElementAdded); + + var removedCheck = await browser.EvaluateScriptAsync($"document.querySelector('#{elementId}') === null"); + + Assert.True(removedCheck.Success); + Assert.True((bool)removedCheck.Result); + } + } + + [Fact] + public async Task ShouldReturnTrueForRemovedNonExistingElement() + { + using (var browser = new ChromiumWebBrowser(CefExample.DefaultUrl)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var selectorResponse = await browser.WaitForSelectorAsync("non-existing", removed:true ); + + Assert.True(selectorResponse.Success); + Assert.False(selectorResponse.ElementAdded); + } + } + + [Fact] + public async Task CanTimeout() + { + const string expected = "The operation has timed out."; + + using (var browser = new ChromiumWebBrowser(CefExample.DefaultUrl)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var exception = await Assert.ThrowsAnyAsync(async () => + { + await browser.WaitForSelectorAsync("#notExist", timeout: TimeSpan.FromMilliseconds(100)); + }); + + Assert.Contains(expected, exception.Message); + + output.WriteLine("Exception {0}", exception.Message); + } + } + + [Fact] + public async Task ShouldTimeoutIfNavigationOccurs() + { + const string expected = "The operation has timed out."; + const string url = CefExample.HelloWorldUrl; + + using (var browser = new ChromiumWebBrowser(CefExample.DefaultUrl)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var exception = await Assert.ThrowsAnyAsync(async () => + { + var navigationTask = browser.WaitForSelectorAsync("non-existant"); + var evaluateTask = browser.EvaluateScriptAsync($"setTimeout(() => window.location.href = '{url}', 100);"); + + await Task.WhenAll(navigationTask, evaluateTask); + }); + + Assert.Contains(expected, exception.Message); + Assert.Contains(url, browser.GetMainFrame().Url); + + output.WriteLine("Exception {0}", exception.Message); + } + } + + [Fact] + public async Task ShouldRespondToNodeAttributeMutation() + { + var html = new HtmlString("
"); + + using (var browser = new ChromiumWebBrowser(html)) + { + var response = await browser.WaitForInitialLoadAsync(); + + Assert.True(response.Success); + + var divFound = false; + var waitForSelector = browser.WaitForSelectorAsync(".zombo").ContinueWith(_ => divFound = true); + + Assert.False(divFound); + + browser.ExecuteScriptAsync("document.querySelector('div').className = 'zombo'"); + + var actual = await waitForSelector; + + Assert.True(actual); + } + } + } +} diff --git a/CefSharp/JavascriptResponse.cs b/CefSharp/JavascriptResponse.cs index 419701542..610f7ffc2 100644 --- a/CefSharp/JavascriptResponse.cs +++ b/CefSharp/JavascriptResponse.cs @@ -3,6 +3,7 @@ // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Generic; +using System.Diagnostics; using System.Runtime.Serialization; using CefSharp.Internals; @@ -15,6 +16,7 @@ namespace CefSharp [KnownType(typeof(object[]))] [KnownType(typeof(JavascriptCallback))] [KnownType(typeof(Dictionary))] + [DebuggerDisplay("Success = {Success}, Message = {Message}, Result = {Result}")] public class JavascriptResponse { /// diff --git a/CefSharp/WaitForSelectorAsyncResponse.cs b/CefSharp/WaitForSelectorAsyncResponse.cs new file mode 100644 index 000000000..5d6d24d69 --- /dev/null +++ b/CefSharp/WaitForSelectorAsyncResponse.cs @@ -0,0 +1,49 @@ +// Copyright © 2022 The CefSharp Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. + +namespace CefSharp +{ + /// + /// WaitForSelectorAsyncResponse + /// + public class WaitForSelectorAsyncResponse + { + /// + /// Element Id + /// + public string ElementId { get; private set; } + /// + /// Tag Name + /// + public string TagName { get; private set; } + /// + /// True if the javascript was executed successfully + /// + public bool Success { get; private set; } + /// + /// Error Message + /// + public string ErrorMessage { get; private set; } + /// + /// True if the element was added to the DOM otherwise false if it was removed + /// + public bool ElementAdded { get; private set; } + + public WaitForSelectorAsyncResponse(bool success, string errorMessage) + { + Success = success; + ErrorMessage = errorMessage; + } + + public WaitForSelectorAsyncResponse(string elementId, string tagName, bool elementAdded) + { + Success = true; + ErrorMessage = string.Empty; + + ElementId = elementId; + TagName = tagName; + ElementAdded = elementAdded; + } + } +} diff --git a/CefSharp/WebBrowserExtensions.cs b/CefSharp/WebBrowserExtensions.cs index 6f164dc39..b83128aef 100644 --- a/CefSharp/WebBrowserExtensions.cs +++ b/CefSharp/WebBrowserExtensions.cs @@ -3,6 +3,7 @@ // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; +using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; @@ -483,7 +484,7 @@ namespace CefSharp /// string script = "document.getElementsByTagName('a')[0].click();"; /// await Task.WhenAll( /// chromiumWebBrowser.WaitForNavigationAsync(), - /// chromiumWebBrowser.EvaluateScriptAsync(jsScript3)); + /// chromiumWebBrowser.EvaluateScriptAsync(script)); /// ]]> /// /// @@ -553,6 +554,128 @@ namespace CefSharp return TaskTimeoutExtensions.WaitAsync(tcs.Task, timeout ?? TimeSpan.FromSeconds(5), cancellationToken); } + /// + /// Waits for a DOM element specified by the string to be added to or removed from the DOM. + /// A simplified version of Puppeteer WaitForSelector. Uses a MutationObserver to wait for the element to become added or removed. + /// + /// ChromiumWebBrowser instance (cannot be null) + /// querySelector for the element e.g. #idOfMyElement + /// timeout + /// + /// (Optional) if true waits for element to be removed from the DOM. If the querySelector immediately resolves + /// to null then the element is considered removed. If false (default) waits for the element to be added to the DOM. + /// + /// A Task that resolves when element specified by selector string is added to or removed from the DOM. + /// + /// + /// + /// + /// + /// + /// This function is typically used in conjunction with javascript that directly or indirectly adds/removes an element from the DOM. + /// Unlike the puppeteer version navigations aren't handled internally, the method will throw a if a navigation + /// occurs whilst waiting to resolve. + /// + public static async Task WaitForSelectorAsync(this IWebBrowser chromiumWebBrowser, string selector, TimeSpan? timeout = null, bool removed = false) + { + const string waitForSelectorFunction = @" + async function waitForSelectorFunction(timeout, selector, waitForRemoved) + { + let timedOut = false; + if (timeout) + setTimeout(() => (timedOut = true), timeout); + + return await pollMutation(); + + async function pollMutation() { + const success = await mutationSelector(selector, waitForRemoved); + if (success) + return Promise.resolve(success); + let fulfill; + const result = new Promise((x) => (fulfill = x)); + const observer = new MutationObserver(async () => { + if (timedOut) { + observer.disconnect(); + fulfill(); + } + const success = await mutationSelector(selector, waitForRemoved); + if (success) { + observer.disconnect(); + fulfill(success); + } + }); + observer.observe(document, { + childList: true, + subtree: true, + attributes: false, + }); + return result; + } + + async function mutationSelector(selector, waitForRemoved) + { + const element = document.querySelector(selector); + + if (!element) + return waitForRemoved; + + if(waitForRemoved && element) + return null; + + let obj = {}; + obj.id = element.id; + obj.nodeValue = element.nodeValue; + obj.localName = element.localName; + obj.tagName = element.tagName; + + return obj; + } + };"; + + if(chromiumWebBrowser == null) + { + throw new ArgumentNullException(nameof(chromiumWebBrowser)); + } + + if(string.IsNullOrEmpty(selector)) + { + throw new ArgumentException($"{nameof(selector)} cannot be null or empty."); + } + + var execute = GetScriptForJavascriptMethodWithArgs("waitForSelectorFunction", new object[] { timeout.HasValue ? timeout.Value.Milliseconds : 5000, selector, removed }); + var query = @"return (async () => {" + Environment.NewLine + waitForSelectorFunction + Environment.NewLine + "return " + execute + Environment.NewLine + "})(); "; + + var response = chromiumWebBrowser.EvaluateScriptAsPromiseAsync(query); + + var timeoutResponse = await TaskTimeoutExtensions.WaitAsync(response, timeout ?? TimeSpan.FromSeconds(5)).ConfigureAwait(continueOnCapturedContext:false); + + if(timeoutResponse.Success) + { + if(removed) + { + if ((bool)timeoutResponse.Result) + { + return new WaitForSelectorAsyncResponse(string.Empty, string.Empty, false); + } + + return new WaitForSelectorAsyncResponse(false, $"Failed to detect DOM change for removed element via selector {selector}"); + } + + var element = (IDictionary)timeoutResponse.Result; + var id = element["id"].ToString(); + var tagName = element["tagName"].ToString(); + + return new WaitForSelectorAsyncResponse(id, tagName, true); + } + + return new WaitForSelectorAsyncResponse(false, timeoutResponse.Message); + } + /// /// Execute Javascript code in the context of this Browser. As the method name implies, the script will be executed /// asynchronously, and the method therefore returns before the script has actually been executed. This simple helper extension