How to use DOMWorld method of PuppeteerSharp.DOMWorld class

Best Puppeteer-sharp code snippet using PuppeteerSharp.DOMWorld.DOMWorld

Frame.cs

Source:Frame.cs Github

copy

Full Screen

...42 internal string Id { get; set; }43 internal string LoaderId { get; set; }44 internal List<string> LifecycleEvents { get; }45 internal string NavigationURL { get; private set; }46 internal DOMWorld MainWorld { get; }47 internal DOMWorld SecondaryWorld { get; }48 internal Frame(FrameManager frameManager, CDPSession client, Frame parentFrame, string frameId)49 {50 FrameManager = frameManager;51 _client = client;52 ParentFrame = parentFrame;53 Id = frameId;54 if (parentFrame != null)55 {56 ParentFrame.ChildFrames.Add(this);57 }58 WaitTasks = new List<WaitTask>();59 LifecycleEvents = new List<string>();60 MainWorld = new DOMWorld(FrameManager, this, FrameManager.TimeoutSettings);61 SecondaryWorld = new DOMWorld(FrameManager, this, FrameManager.TimeoutSettings);62 }63 #region Properties64 /// <summary>65 /// Gets the child frames of the this frame66 /// </summary>67 public List<Frame> ChildFrames { get; } = new List<Frame>();68 /// <summary>69 /// Gets the frame's name attribute as specified in the tag70 /// If the name is empty, returns the id attribute instead71 /// </summary>72 public string Name { get; private set; }73 /// <summary>74 /// Gets the frame's url75 /// </summary>...

Full Screen

Full Screen

FrameManager.cs

Source:FrameManager.cs Github

copy

Full Screen

...219 private async Task OnExecutionContextCreatedAsync(ContextPayload contextPayload)220 {221 var frameId = contextPayload.AuxData?.FrameId;222 var frame = !string.IsNullOrEmpty(frameId) ? await GetFrameAsync(frameId).ConfigureAwait(false) : null;223 DOMWorld world = null;224 if (frame != null)225 {226 if (contextPayload.AuxData?.IsDefault == true)227 {228 world = frame.MainWorld;229 }230 else if (contextPayload.Name == UtilityWorldName && !frame.SecondaryWorld.HasContext)231 {232 // In case of multiple sessions to the same target, there's a race between233 // connections so we might end up creating multiple isolated worlds.234 // We can use either.235 world = frame.SecondaryWorld;236 }237 }238 if (contextPayload.AuxData?.Type == DOMWorldType.Isolated)239 {240 _isolatedWorlds.Add(contextPayload.Name);241 }242 var context = new ExecutionContext(Client, contextPayload, world);243 if (world != null)244 {245 world.SetContext(context);246 }247 _contextIdToContext[contextPayload.Id] = context;248 }249 private void OnFrameDetached(BasicFrameResponse e)250 {251 if (_frames.TryGetValue(e.FrameId, out var frame))252 {...

Full Screen

Full Screen

DOMWorld.cs

Source:DOMWorld.cs Github

copy

Full Screen

...4using System.Collections.Generic;5using System.Threading.Tasks;6namespace PuppeteerSharp7{8 internal class DOMWorld9 {10 private readonly FrameManager _frameManager;11 private readonly TimeoutSettings _timeoutSettings;12 private bool _detached;13 private TaskCompletionSource<ExecutionContext> _contextResolveTaskWrapper;14 private TaskCompletionSource<ElementHandle> _documentCompletionSource;15 internal List<WaitTask> WaitTasks { get; set; }16 internal Frame Frame { get; }17 public DOMWorld(FrameManager frameManager, Frame frame, TimeoutSettings timeoutSettings)18 {19 _frameManager = frameManager;20 Frame = frame;21 _timeoutSettings = timeoutSettings;22 SetContext(null);23 WaitTasks = new List<WaitTask>();24 _detached = false;25 }26 internal void SetContext(ExecutionContext context)27 {28 if (context != null)29 {30 _contextResolveTaskWrapper.TrySetResult(context);31 foreach (var waitTask in WaitTasks)...

Full Screen

Full Screen

ExecutionContext.cs

Source:ExecutionContext.cs Github

copy

Full Screen

...20 private readonly string EvaluationScriptSuffix = $"//# sourceURL={EvaluationScriptUrl}";21 private static readonly Regex _sourceUrlRegex = new Regex(@"^[\040\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$", RegexOptions.Multiline);22 private readonly CDPSession _client;23 private readonly int _contextId;24 internal DOMWorld World { get; }25 internal ExecutionContext(26 CDPSession client,27 ContextPayload contextPayload,28 DOMWorld world)29 {30 _client = client;31 _contextId = contextPayload.Id;32 World = world;33 }34 /// <summary>35 /// Frame associated with this execution context.36 /// </summary>37 /// <remarks>38 /// NOTE Not every execution context is associated with a frame. For example, workers and extensions have execution contexts that are not associated with frames.39 /// </remarks>40 public Frame Frame => World?.Frame;41 /// <summary>42 /// Executes a script in browser context43 /// </summary>44 /// <param name="script">Script to be evaluated in browser context</param>45 /// <remarks>46 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.47 /// </remarks>48 /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>49 /// <seealso cref="EvaluateExpressionHandleAsync(string)"/>50 /// <returns>Task which resolves to script return value</returns>51 public Task<JToken> EvaluateExpressionAsync(string script) => EvaluateExpressionAsync<JToken>(script);52 /// <summary>53 /// Executes a script in browser context54 /// </summary>55 /// <typeparam name="T">The type to deserialize the result to</typeparam>56 /// <param name="script">Script to be evaluated in browser context</param>57 /// <remarks>58 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.59 /// </remarks>60 /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>61 /// <seealso cref="EvaluateExpressionHandleAsync(string)"/>62 /// <returns>Task which resolves to script return value</returns>63 public Task<T> EvaluateExpressionAsync<T>(string script)64 => RemoteObjectTaskToObject<T>(EvaluateExpressionInternalAsync(true, script));65 internal async Task<JSHandle> EvaluateExpressionHandleAsync(string script)66 => CreateJSHandle(await EvaluateExpressionInternalAsync(false, script).ConfigureAwait(false));67 /// <summary>68 /// Executes a function in browser context69 /// </summary>70 /// <param name="script">Script to be evaluated in browser context</param>71 /// <param name="args">Arguments to pass to script</param>72 /// <remarks>73 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.74 /// <see cref="JSHandle"/> instances can be passed as arguments75 /// </remarks>76 /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>77 /// <returns>Task which resolves to script return value</returns>78 public Task<JToken> EvaluateFunctionAsync(string script, params object[] args) => EvaluateFunctionAsync<JToken>(script, args);79 /// <summary>80 /// Executes a function in browser context81 /// </summary>82 /// <typeparam name="T">The type to deserialize the result to</typeparam>83 /// <param name="script">Script to be evaluated in browser context</param>84 /// <param name="args">Arguments to pass to script</param>85 /// <remarks>86 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.87 /// <see cref="JSHandle"/> instances can be passed as arguments88 /// </remarks>89 /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>90 /// <returns>Task which resolves to script return value</returns>91 public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)92 => RemoteObjectTaskToObject<T>(EvaluateFunctionInternalAsync(true, script, args));93 internal async Task<JSHandle> EvaluateFunctionHandleAsync(string script, params object[] args)94 => CreateJSHandle(await EvaluateFunctionInternalAsync(false, script, args).ConfigureAwait(false));95 /// <summary>96 /// The method iterates JavaScript heap and finds all the objects with the given prototype.97 /// </summary>98 /// <returns>A task which resolves to a handle to an array of objects with this prototype.</returns>99 /// <param name="prototypeHandle">A handle to the object prototype.</param>100 public async Task<JSHandle> QueryObjectsAsync(JSHandle prototypeHandle)101 {102 if (prototypeHandle.Disposed)103 {104 throw new PuppeteerException("Prototype JSHandle is disposed!");105 }106 if (prototypeHandle.RemoteObject.ObjectId == null)107 {108 throw new PuppeteerException("Prototype JSHandle must not be referencing primitive value");109 }110 var response = await _client.SendAsync<RuntimeQueryObjectsResponse>("Runtime.queryObjects", new RuntimeQueryObjectsRequest111 {112 PrototypeObjectId = prototypeHandle.RemoteObject.ObjectId113 }).ConfigureAwait(false);114 return CreateJSHandle(response.Objects);115 }116 private async Task<T> RemoteObjectTaskToObject<T>(Task<RemoteObject> remote)117 {118 var response = await remote.ConfigureAwait(false);119 return response == null ? default : (T)RemoteObjectHelper.ValueFromRemoteObject<T>(response);120 }121 private Task<RemoteObject> EvaluateExpressionInternalAsync(bool returnByValue, string script)122 => ExecuteEvaluationAsync("Runtime.evaluate", new Dictionary<string, object>123 {124 ["expression"] = _sourceUrlRegex.IsMatch(script) ? script : $"{script}\n{EvaluationScriptSuffix}",125 ["contextId"] = _contextId,126 ["returnByValue"] = returnByValue,127 ["awaitPromise"] = true,128 ["userGesture"] = true129 });130 private Task<RemoteObject> EvaluateFunctionInternalAsync(bool returnByValue, string script, params object[] args)131 => ExecuteEvaluationAsync("Runtime.callFunctionOn", new RuntimeCallFunctionOnRequest132 {133 FunctionDeclaration = $"{script}\n{EvaluationScriptSuffix}\n",134 ExecutionContextId = _contextId,135 Arguments = args.Select(FormatArgument),136 ReturnByValue = returnByValue,137 AwaitPromise = true,138 UserGesture = true139 });140 private async Task<RemoteObject> ExecuteEvaluationAsync(string method, object args)141 {142 try143 {144 var response = await _client.SendAsync<EvaluateHandleResponse>(method, args).ConfigureAwait(false);145 if (response.ExceptionDetails != null)146 {147 throw new EvaluationFailedException("Evaluation failed: " +148 GetExceptionMessage(response.ExceptionDetails));149 }150 return response.Result;151 }152 catch (MessageException ex)153 {154 if (ex.Message.Contains("Object reference chain is too long") ||155 ex.Message.Contains("Object couldn't be returned by value"))156 {157 return default;158 }159 throw new EvaluationFailedException(ex.Message, ex);160 }161 }162 internal JSHandle CreateJSHandle(RemoteObject remoteObject)163 => remoteObject.Subtype == RemoteObjectSubtype.Node && Frame != null164 ? new ElementHandle(this, _client, remoteObject, Frame.FrameManager.Page, Frame.FrameManager)165 : new JSHandle(this, _client, remoteObject);166 private object FormatArgument(object arg)167 {168 switch (arg)169 {170 case BigInteger big:171 return new { unserializableValue = $"{big}n" };172 case int integer when integer == -0:173 return new { unserializableValue = "-0" };174 case double d:175 if (double.IsPositiveInfinity(d))176 {177 return new { unserializableValue = "Infinity" };178 }179 if (double.IsNegativeInfinity(d))180 {181 return new { unserializableValue = "-Infinity" };182 }183 if (double.IsNaN(d))184 {185 return new { unserializableValue = "NaN" };186 }187 break;188 case JSHandle objectHandle:189 return objectHandle.FormatArgument(this);190 }191 return new RuntimeCallFunctionOnRequestArgument192 {193 Value = arg194 };195 }196 private static string GetExceptionMessage(EvaluateExceptionResponseDetails exceptionDetails)197 {198 if (exceptionDetails.Exception != null)199 {200 return exceptionDetails.Exception.Description ?? exceptionDetails.Exception.Value;201 }202 var message = exceptionDetails.Text;203 if (exceptionDetails.StackTrace != null)204 {205 foreach (var callframe in exceptionDetails.StackTrace.CallFrames)206 {207 var location = $"{callframe.Url}:{callframe.LineNumber}:{callframe.ColumnNumber}";208 var functionName = string.IsNullOrEmpty(callframe.FunctionName) ? "<anonymous>" : callframe.FunctionName;209 message += $"\n at ${functionName} (${location})";210 }211 }212 return message;213 }214 internal async Task<ElementHandle> AdoptElementHandleASync(ElementHandle elementHandle)215 {216 if (elementHandle.ExecutionContext == this)217 {218 throw new PuppeteerException("Cannot adopt handle that already belongs to this execution context");219 }220 if (World == null)221 {222 throw new PuppeteerException("Cannot adopt handle without DOMWorld");223 }224 var nodeInfo = await _client.SendAsync<DomDescribeNodeResponse>("DOM.describeNode", new DomDescribeNodeRequest225 {226 ObjectId = elementHandle.RemoteObject.ObjectId227 }).ConfigureAwait(false);228 var obj = await _client.SendAsync<DomResolveNodeResponse>("DOM.resolveNode", new DomResolveNodeRequest229 {230 BackendNodeId = nodeInfo.Node.BackendNodeId,231 ExecutionContextId = _contextId232 }).ConfigureAwait(false);233 return CreateJSHandle(obj.Object) as ElementHandle;234 }235 }236}...

Full Screen

Full Screen

WaitTask.cs

Source:WaitTask.cs Github

copy

Full Screen

...5namespace PuppeteerSharp6{7 internal class WaitTask8 {9 private readonly DOMWorld _world;10 private readonly string _predicateBody;11 private readonly WaitForFunctionPollingOption _polling;12 private readonly int? _pollingInterval;13 private readonly int _timeout;14 private readonly object[] _args;15 private readonly string _title;16 private readonly Task _timeoutTimer;17 private readonly CancellationTokenSource _cts;18 private readonly TaskCompletionSource<JSHandle> _taskCompletion;19 private int _runCount;20 private bool _terminated;21 private const string WaitForPredicatePageFunction = @"22async function waitForPredicatePageFunction(predicateBody, polling, timeout, ...args) {23 const predicate = new Function('...args', predicateBody);24 let timedOut = false;25 if (timeout)26 setTimeout(() => timedOut = true, timeout);27 if (polling === 'raf')28 return await pollRaf();29 if (polling === 'mutation')30 return await pollMutation();31 if (typeof polling === 'number')32 return await pollInterval(polling);33 /**34 * @return {!Promise<*>}35 */36 function pollMutation() {37 const success = predicate.apply(null, args);38 if (success)39 return Promise.resolve(success);40 let fulfill;41 const result = new Promise(x => fulfill = x);42 const observer = new MutationObserver(mutations => {43 if (timedOut) {44 observer.disconnect();45 fulfill();46 }47 const success = predicate.apply(null, args);48 if (success) {49 observer.disconnect();50 fulfill(success);51 }52 });53 observer.observe(document, {54 childList: true,55 subtree: true,56 attributes: true57 });58 return result;59 }60 /**61 * @return {!Promise<*>}62 */63 function pollRaf() {64 let fulfill;65 const result = new Promise(x => fulfill = x);66 onRaf();67 return result;68 function onRaf() {69 if (timedOut) {70 fulfill();71 return;72 }73 const success = predicate.apply(null, args);74 if (success)75 fulfill(success);76 else77 requestAnimationFrame(onRaf);78 }79 }80 /**81 * @param {number} pollInterval82 * @return {!Promise<*>}83 */84 function pollInterval(pollInterval) {85 let fulfill;86 const result = new Promise(x => fulfill = x);87 onTimeout();88 return result;89 function onTimeout() {90 if (timedOut) {91 fulfill();92 return;93 }94 const success = predicate.apply(null, args);95 if (success)96 fulfill(success);97 else98 setTimeout(onTimeout, pollInterval);99 }100 }101}";102 internal WaitTask(103 DOMWorld world,104 string predicateBody,105 bool isExpression,106 string title,107 WaitForFunctionPollingOption polling,108 int? pollingInterval,109 int timeout,110 object[] args = null)111 {112 if (string.IsNullOrEmpty(predicateBody))113 {114 throw new ArgumentNullException(nameof(predicateBody));115 }116 if (pollingInterval <= 0)117 {...

Full Screen

Full Screen

DOMWorldType.cs

Source:DOMWorldType.cs Github

copy

Full Screen

...3using PuppeteerSharp.Helpers.Json;4namespace PuppeteerSharp5{6 [JsonConverter(typeof(FlexibleStringEnumConverter), Other)]7 internal enum DOMWorldType8 {9 Other,10 [EnumMember(Value = "isolated")]11 Isolated12 }13}...

Full Screen

Full Screen

ContextPayloadAuxData.cs

Source:ContextPayloadAuxData.cs Github

copy

Full Screen

...4 internal class ContextPayloadAuxData5 {6 public string FrameId { get; set; }7 public bool IsDefault { get; set; }8 public DOMWorldType Type { get; set; }9 }10}...

Full Screen

Full Screen

DOMWorld

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });10 var page = await browser.NewPageAsync();11 await page.EvaluateExpressionAsync("document.querySelector('input').value = 'PuppeteerSharp'");12 var input = await page.QuerySelectorAsync("input");13 var inputValue = await page.EvaluateFunctionAsync<string>("input => input.value", input);14 Console.WriteLine(inputValue);15 await browser.CloseAsync();16 }17 }18}

Full Screen

Full Screen

DOMWorld

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var options = new LaunchOptions { Headless = true };9 using (var browser = await Puppeteer.LaunchAsync(options))10 using (var page = await browser.NewPageAsync())11 {12 var title = await page.EvaluateFunctionAsync<string>("() => document.title");13 Console.WriteLine(title);14 }15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 var options = new LaunchOptions { Headless = true };26 using (var browser = await Puppeteer.LaunchAsync(options))27 using (var page = await browser.NewPageAsync())28 {29 var title = await page.EvaluateExpressionAsync<string>("document.title");30 Console.WriteLine(title);31 }32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 static async Task Main(string[] args)41 {42 var options = new LaunchOptions { Headless = true };43 using (var browser = await Puppeteer.LaunchAsync(options))44 using (var page = await browser.NewPageAsync())45 {46 var title = await page.EvaluateFunctionHandleAsync("() => document.title");47 Console.WriteLine(title);48 }49 }50 }51}52using System;53using System.Threading.Tasks;54using PuppeteerSharp;55{56 {57 static async Task Main(string[] args)58 {59 var options = new LaunchOptions { Headless = true };60 using (var browser = await Puppet

Full Screen

Full Screen

DOMWorld

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2var result = await page.EvaluateFunctionAsync("() => document.title");3var page = await browser.NewPageAsync();4var result = await page.EvaluateExpressionAsync("document.title");5var page = await browser.NewPageAsync();6var element = await page.QuerySelectorAsync("input[name='q']");7await element.TypeAsync("Puppeteer Sharp");8var page = await browser.NewPageAsync();9var elements = await page.QuerySelectorAllAsync("a");10foreach (var element in elements)11{12 var href = await element.EvaluateFunctionAsync<string>("node => node.href");13 Console.WriteLine(href);14}15var page = await browser.NewPageAsync();16var result = await page.EvaluateFunctionAsync("() => document.title");17var page = await browser.NewPageAsync();18var element = await page.QuerySelectorAsync("input[name='q']");19var result = await element.EvaluateFunctionAsync("node => node.getAttribute('name')");20var page = await browser.NewPageAsync();21var result = await page.EvaluateFunctionAsync("() => document.title");22var page = await browser.NewPageAsync();

Full Screen

Full Screen

DOMWorld

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.SwitchToFrameAsync("iframeResult");13 string text = await page.EvaluateExpressionAsync<string>("document.getElementById('demo').innerHTML");14 Console.WriteLine($"The value of the element with id=\"demo\" is: {text}");15 Console.ReadKey();16 await browser.CloseAsync();17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 var browser = await Puppeteer.LaunchAsync(new LaunchOptions28 {29 });30 var page = await browser.NewPageAsync();

Full Screen

Full Screen

DOMWorld

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 Args = new string[] { "--start-maximized" }10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 using (var page = await browser.NewPageAsync())14 {15 await page.WaitForSelectorAsync("input[name='q']");16 await page.TypeAsync("input[name='q']", "PuppeteerSharp");17 await page.ClickAsync("input[name='btnK']");18 await page.WaitForNavigationAsync();19 string result = await page.EvaluateExpressionAsync<string>("document.querySelector('div#resultStats').innerText");20 Console.WriteLine(result);21 }22 }23 }24 }25}26using System;27using System.Threading.Tasks;28using PuppeteerSharp;29{30 {31 static async Task Main(string[] args)32 {33 {34 Args = new string[] { "--start-maximized" }35 };36 using (var browser = await Puppeteer.LaunchAsync(options))37 {38 using (var page = await browser.NewPageAsync())39 {40 await page.WaitForSelectorAsync("input[name='q']");41 await page.TypeAsync("input[name='q']", "Puppet

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful