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
This commit is contained in:
Alex Maitland
2022-05-30 12:00:18 +10:00
committed by GitHub
parent 61f581346a
commit d701cee655
4 changed files with 379 additions and 1 deletions
@@ -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<TimeoutException>(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<TimeoutException>(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("<div class='notZombo'></div>");
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);
}
}
}
}
+2
View File
@@ -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<string, object>))]
[DebuggerDisplay("Success = {Success}, Message = {Message}, Result = {Result}")]
public class JavascriptResponse
{
/// <summary>
+49
View File
@@ -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
{
/// <summary>
/// WaitForSelectorAsyncResponse
/// </summary>
public class WaitForSelectorAsyncResponse
{
/// <summary>
/// Element Id
/// </summary>
public string ElementId { get; private set; }
/// <summary>
/// Tag Name
/// </summary>
public string TagName { get; private set; }
/// <summary>
/// True if the javascript was executed successfully
/// </summary>
public bool Success { get; private set; }
/// <summary>
/// Error Message
/// </summary>
public string ErrorMessage { get; private set; }
/// <summary>
/// True if the element was added to the DOM otherwise false if it was removed
/// </summary>
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;
}
}
}
+124 -1
View File
@@ -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));
/// ]]>
/// </code>
/// </example>
@@ -553,6 +554,128 @@ namespace CefSharp
return TaskTimeoutExtensions.WaitAsync(tcs.Task, timeout ?? TimeSpan.FromSeconds(5), cancellationToken);
}
/// <summary>
/// Waits for a DOM element specified by the <paramref name="selector"/> 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.
/// </summary>
/// <param name="chromiumWebBrowser">ChromiumWebBrowser instance (cannot be null)</param>
/// <param name="selector">querySelector for the element e.g. #idOfMyElement</param>
/// <param name="timeout">timeout</param>
/// <param name="removed">
/// (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.
/// </param>
/// <returns>A Task that resolves when element specified by selector string is added to or removed from the DOM.</returns>
/// <example>
/// <code>
/// <![CDATA[
/// string script = "const newDiv = document.createElement('div'); newDiv.id = 'myElement'; document.body.append(newDiv);";
/// await Task.WhenAll(
/// browser.WaitForSelectorAsync("#myElement");,
/// chromiumWebBrowser.EvaluateScriptAsync(script));
/// ]]>
/// </code>
/// </example>
/// <remarks>
/// 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 <see cref="TimeoutException"/> if a navigation
/// occurs whilst waiting to resolve.
/// </remarks>
public static async Task<WaitForSelectorAsyncResponse> 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<string, object>)timeoutResponse.Result;
var id = element["id"].ToString();
var tagName = element["tagName"].ToString();
return new WaitForSelectorAsyncResponse(id, tagName, true);
}
return new WaitForSelectorAsyncResponse(false, timeoutResponse.Message);
}
/// <summary>
/// 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