How to use DOMWorld class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.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

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

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 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 var world = await page.CreateIsolatedWorldAsync("myWorld");13 var document = await world.GetDocumentAsync();14 var body = await document.QuerySelectorAsync("body");15 await body.SetContentAsync("<h1>Hello World</h1>");16 Console.WriteLine("Hello World!");17 }18 }19}20const puppeteer = require('puppeteer');21(async () => {22 const browser = await puppeteer.launch();23 const page = await browser.newPage();24 const world = await page.createIsolatedWorld('myWorld');25 const document = await world.getDocument();26 const body = await document.querySelector('body');27 await body.setContent('<h1>Hello World</h1>');28 await browser.close();29})();30using System;31using System.Threading.Tasks;32using PuppeteerSharp;33{34 {35 static async Task Main(string[] args)36 {37 var browser = await Puppeteer.LaunchAsync(new LaunchOptions38 {39 });40 var page = await browser.NewPageAsync();

Full Screen

Full Screen

DOMWorld

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--start-maximized" }4});5var page = await browser.NewPageAsync();6var searchBox = await page.QuerySelectorAsync("input[name=q]");7await searchBox.ClickAsync();8await page.Keyboard.TypeAsync("puppeteer");9await page.Keyboard.PressAsync("Enter");10await page.WaitForNavigationAsync();11await page.ScreenshotAsync("google.png");12await page.CloseAsync();13await browser.CloseAsync();14var browser = await Puppeteer.LaunchAsync(new LaunchOptions15{16 Args = new string[] { "--start-maximized" }17});18var page = await browser.NewPageAsync();19await page.ScreenshotAsync("google.png");20await page.CloseAsync();21await browser.CloseAsync();22var browser = await Puppeteer.LaunchAsync(new LaunchOptions23{24 Args = new string[] { "--start-maximized" }25});26var page = await browser.NewPageAsync();27await page.SetViewportAsync(new ViewPortOptions28{29});30await page.ScreenshotAsync("google.png");31await page.CloseAsync();32await browser.CloseAsync();33var browser = await Puppeteer.LaunchAsync(new LaunchOptions34{35 Args = new string[] { "--start-maximized" }36});37var page = await browser.NewPageAsync();38var searchBox = await page.QuerySelectorAsync("input[name=q]");39await searchBox.ClickAsync();40await page.Keyboard.TypeAsync("puppeteer");41await page.Keyboard.PressAsync("Enter");42await page.WaitForNavigationAsync();43await page.ScreenshotAsync("google.png");44await page.CloseAsync();45await browser.CloseAsync();

Full Screen

Full Screen

DOMWorld

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using PuppeteerSharp.Media;5{6 {7 static async Task Main(string[] args)8 {9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png", new ScreenshotOptions { FullPage = true });14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21using PuppeteerSharp.Media;22{23 {24 static async Task Main(string[] args)25 {26 var browser = await Puppeteer.LaunchAsync(new LaunchOptions27 {28 });29 var page = await browser.NewPageAsync();30 await page.ScreenshotAsync("google.png", new ScreenshotOptions { FullPage = true });31 await browser.CloseAsync();32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38using PuppeteerSharp.Media;39{40 {41 static async Task Main(string[] args)42 {43 var browser = await Puppeteer.LaunchAsync(new LaunchOptions44 {45 });46 var page = await browser.NewPageAsync();47 await page.ScreenshotAsync("google.png", new ScreenshotOptions { FullPage = true });48 await browser.CloseAsync();49 }50 }51}52using System;53using System.Threading.Tasks;54using PuppeteerSharp;55using PuppeteerSharp.Media;56{57 {58 static async Task Main(string[] args)59 {60 var browser = await Puppeteer.LaunchAsync(new LaunchOptions61 {62 });

Full Screen

Full Screen

DOMWorld

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",15 Args = new string[] { "--no-sandbox" }16 });17 var page = await browser.NewPageAsync();18 await page.ScreenshotAsync("baidu.png");19 await page.EvaluateFunctionAsync("() =>{document.getElementById('kw').value = 'puppeteer';}");20 await page.ClickAsync("#su");21 await page.ScreenshotAsync("puppeteer.png");22 await browser.CloseAsync();23 }24 }25}26using System;27using System.Threading.Tasks;28using PuppeteerSharp;29{30 {31 static void Main(string[] args)32 {33 MainAsync().Wait();34 }35 static async Task MainAsync()36 {37 var browser = await Puppeteer.LaunchAsync(new LaunchOptions38 {39 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",40 Args = new string[] { "--no-sandbox" }41 });42 var page = await browser.NewPageAsync();43 await page.ScreenshotAsync("baidu.png");44 await page.EvaluateFunctionAsync("() =>{document.getElementById('kw').value = 'puppeteer';}");45 await page.ClickAsync("#su");46 await page.ScreenshotAsync("puppeteer.png");

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