How to use GetExecutionContextAsync method of PuppeteerSharp.Frame class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.GetExecutionContextAsync

Page.cs

Source:Page.cs Github

copy

Full Screen

...288 /// </remarks>289 /// <returns>Task which resolves to script return value</returns>290 public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)291 {292 var context = await MainFrame.GetExecutionContextAsync();293 return await context.EvaluateExpressionHandleAsync(script);294 }295 /// <summary>296 /// Executes a script in browser context297 /// </summary>298 /// <param name="pageFunction">Script to be evaluated in browser context</param>299 /// <param name="args">Function arguments</param>300 /// <remarks>301 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.302 /// <see cref="JSHandle"/> instances can be passed as arguments303 /// </remarks>304 /// <returns>Task which resolves to script return value</returns>305 public async Task<JSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)306 {307 var context = await MainFrame.GetExecutionContextAsync();308 return await context.EvaluateFunctionHandleAsync(pageFunction, args);309 }310 /// <summary>311 /// Adds a function which would be invoked in one of the following scenarios:312 /// - whenever the page is navigated313 /// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame314 /// </summary>315 /// <param name="pageFunction">Function to be evaluated in browser context</param>316 /// <param name="args">Arguments to pass to <c>pageFunction</c></param>317 /// <remarks>318 /// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.319 /// </remarks>320 /// <example>321 /// An example of overriding the navigator.languages property before the page loads:322 /// <code>323 /// var overrideNavigatorLanguages = @"Object.defineProperty(navigator, 'languages', {324 /// get: function() {325 /// return ['en-US', 'en', 'bn'];326 /// };327 /// });";328 /// await page.EvaluateOnNewDocumentAsync(overrideNavigatorLanguages);329 /// </code>330 /// </example>331 /// <returns>Task</returns>332 public Task EvaluateOnNewDocumentAsync(string pageFunction, params object[] args)333 {334 var source = EvaluationString(pageFunction, args);335 return Client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new { source });336 }337 /// <summary>338 /// The method iterates JavaScript heap and finds all the objects with the given prototype.339 /// Shortcut for <c>page.MainFrame.GetExecutionContextAsync().QueryObjectsAsync(prototypeHandle)</c>.340 /// </summary>341 /// <returns>A task which resolves to a handle to an array of objects with this prototype.</returns>342 /// <param name="prototypeHandle">A handle to the object prototype.</param>343 public async Task<JSHandle> QueryObjectsAsync(JSHandle prototypeHandle)344 {345 var context = await MainFrame.GetExecutionContextAsync();346 return await context.QueryObjectsAsync(prototypeHandle);347 }348 /// <summary>349 /// Activating request interception enables <see cref="Request.AbortAsync(RequestAbortErrorCode)">request.AbortAsync</see>, 350 /// <see cref="Request.ContinueAsync(Payload)">request.ContinueAsync</see> and <see cref="Request.RespondAsync(ResponseData)">request.RespondAsync</see> methods.351 /// </summary>352 /// <returns>The request interception task.</returns>353 /// <param name="value">Whether to enable request interception..</param>354 public Task SetRequestInterceptionAsync(bool value)355 => _networkManager.SetRequestInterceptionAsync(value);356 /// <summary>357 /// Set offline mode for the page.358 /// </summary>359 /// <returns>Result task</returns>...

Full Screen

Full Screen

Frame.cs

Source:Frame.cs Github

copy

Full Screen

...136 /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>137 /// <seealso cref="Page.EvaluateExpressionAsync{T}(string)"/>138 public async Task<JToken> EvaluateExpressionAsync(string script)139 {140 var context = await GetExecutionContextAsync().ConfigureAwait(false);141 return await context.EvaluateExpressionAsync<JToken>(script).ConfigureAwait(false);142 }143 /// <summary>144 /// Executes a script in browser context145 /// </summary>146 /// <typeparam name="T">The type to deserialize the result to</typeparam>147 /// <param name="script">Script to be evaluated in browser context</param>148 /// <remarks>149 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.150 /// </remarks>151 /// <returns>Task which resolves to script return value</returns>152 /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>153 /// <seealso cref="Page.EvaluateExpressionAsync{T}(string)"/>154 public async Task<T> EvaluateExpressionAsync<T>(string script)155 {156 var context = await GetExecutionContextAsync().ConfigureAwait(false);157 return await context.EvaluateExpressionAsync<T>(script).ConfigureAwait(false);158 }159 /// <summary>160 /// Executes a function in browser context161 /// </summary>162 /// <param name="script">Script to be evaluated in browser context</param>163 /// <param name="args">Arguments to pass to script</param>164 /// <remarks>165 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.166 /// <see cref="JSHandle"/> instances can be passed as arguments167 /// </remarks>168 /// <returns>Task which resolves to script return value</returns>169 /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>170 /// <seealso cref="Page.EvaluateFunctionAsync{T}(string, object[])"/>171 public async Task<JToken> EvaluateFunctionAsync(string script, params object[] args)172 {173 var context = await GetExecutionContextAsync().ConfigureAwait(false);174 return await context.EvaluateFunctionAsync<JToken>(script, args).ConfigureAwait(false);175 }176 /// <summary>177 /// Executes a function in browser context178 /// </summary>179 /// <typeparam name="T">The type to deserialize the result to</typeparam>180 /// <param name="script">Script to be evaluated in browser context</param>181 /// <param name="args">Arguments to pass to script</param>182 /// <remarks>183 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.184 /// <see cref="JSHandle"/> instances can be passed as arguments185 /// </remarks>186 /// <returns>Task which resolves to script return value</returns>187 /// <seealso cref="EvaluateExpressionAsync{T}(string)"/>188 /// <seealso cref="Page.EvaluateFunctionAsync{T}(string, object[])"/>189 public async Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)190 {191 var context = await GetExecutionContextAsync().ConfigureAwait(false);192 return await context.EvaluateFunctionAsync<T>(script, args).ConfigureAwait(false);193 }194 /// <summary>195 /// Passes an expression to the <see cref="ExecutionContext.EvaluateExpressionHandleAsync(string)"/>, returns a <see cref="Task"/>, then <see cref="ExecutionContext.EvaluateExpressionHandleAsync(string)"/> would wait for the <see cref="Task"/> to resolve and return its value.196 /// </summary>197 /// <example>198 /// <code>199 /// var frame = page.MainFrame;200 /// const handle = Page.MainFrame.EvaluateExpressionHandleAsync("1 + 2");201 /// </code>202 /// </example>203 /// <returns>Resolves to the return value of <paramref name="script"/></returns>204 /// <param name="script">Expression to be evaluated in the <seealso cref="ExecutionContext"/></param>205 public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)206 {207 var context = await GetExecutionContextAsync().ConfigureAwait(false);208 return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);209 }210 /// <summary>211 /// Passes a function to the <see cref="ExecutionContext.EvaluateFunctionAsync(string, object[])"/>, returns a <see cref="Task"/>, then <see cref="ExecutionContext.EvaluateFunctionHandleAsync(string, object[])"/> would wait for the <see cref="Task"/> to resolve and return its value.212 /// </summary>213 /// <example>214 /// <code>215 /// var frame = page.MainFrame;216 /// const handle = Page.MainFrame.EvaluateFunctionHandleAsync("() => Promise.resolve(self)");217 /// return handle; // Handle for the global object.218 /// </code>219 /// <see cref="JSHandle"/> instances can be passed as arguments to the <see cref="ExecutionContext.EvaluateFunctionAsync(string, object[])"/>:220 /// 221 /// const handle = await Page.MainFrame.EvaluateExpressionHandleAsync("document.body");222 /// const resultHandle = await Page.MainFrame.EvaluateFunctionHandleAsync("body => body.innerHTML", handle);223 /// return await resultHandle.JsonValueAsync(); // prints body's innerHTML224 /// </example>225 /// <returns>Resolves to the return value of <paramref name="function"/></returns>226 /// <param name="function">Function to be evaluated in the <see cref="ExecutionContext"/></param>227 /// <param name="args">Arguments to pass to <paramref name="function"/></param>228 public async Task<JSHandle> EvaluateFunctionHandleAsync(string function, params object[] args)229 {230 var context = await GetExecutionContextAsync().ConfigureAwait(false);231 return await context.EvaluateFunctionHandleAsync(function, args).ConfigureAwait(false);232 }233 /// <summary>234 /// Gets the <see cref="ExecutionContext"/> associated with the frame.235 /// </summary>236 /// <returns><see cref="ExecutionContext"/> associated with the frame.</returns>237 public Task<ExecutionContext> GetExecutionContextAsync() => _contextResolveTaskWrapper.Task;238 /// <summary>239 /// Waits for a selector to be added to the DOM240 /// </summary>241 /// <param name="selector">A selector of an element to wait for</param>242 /// <param name="options">Optional waiting parameters</param>243 /// <returns>A task that resolves when element specified by selector string is added to DOM</returns>244 /// <seealso cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>245 /// <seealso cref="Page.WaitForSelectorAsync(string, WaitForSelectorOptions)"/>246 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>247 public Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)248 => WaitForSelectorOrXPathAsync(selector, false, options);249 /// <summary>250 /// Waits for a selector to be added to the DOM251 /// </summary>252 /// <param name="xpath">A xpath selector of an element to wait for</param>253 /// <param name="options">Optional waiting parameters</param>254 /// <returns>A task that resolves when element specified by selector string is added to DOM</returns>255 /// <example>256 /// <code>257 /// <![CDATA[258 /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());259 /// var page = await browser.NewPageAsync();260 /// string currentURL = null;261 /// page.MainFrame262 /// .WaitForXPathAsync("//img")263 /// .ContinueWith(_ => Console.WriteLine("First URL with image: " + currentURL));264 /// foreach (var current in new[] { "https://example.com", "https://google.com", "https://bbc.com" })265 /// {266 /// currentURL = current;267 /// await page.GoToAsync(currentURL);268 /// }269 /// await browser.CloseAsync();270 /// ]]>271 /// </code>272 /// </example>273 /// <seealso cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>274 /// <seealso cref="Page.WaitForXPathAsync(string, WaitForSelectorOptions)"/>275 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>276 public Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)277 => WaitForSelectorOrXPathAsync(xpath, true, options);278 /// <summary>279 /// Waits for a timeout280 /// </summary>281 /// <param name="milliseconds"></param>282 /// <returns>A task that resolves when after the timeout</returns>283 /// <seealso cref="Page.WaitForTimeoutAsync(int)"/>284 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>285 public Task WaitForTimeoutAsync(int milliseconds) => Task.Delay(milliseconds);286 /// <summary>287 /// Waits for a function to be evaluated to a truthy value288 /// </summary>289 /// <param name="script">Function to be evaluated in browser context</param>290 /// <param name="options">Optional waiting parameters</param>291 /// <param name="args">Arguments to pass to <c>script</c></param>292 /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>293 /// <seealso cref="Page.WaitForFunctionAsync(string, WaitForFunctionOptions, object[])"/>294 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>295 public Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)296 => new WaitTask(this, script, false, "function", options.Polling, options.PollingInterval, options.Timeout, args).Task;297 /// <summary>298 /// Waits for an expression to be evaluated to a truthy value299 /// </summary>300 /// <param name="script">Expression to be evaluated in browser context</param>301 /// <param name="options">Optional waiting parameters</param>302 /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>303 /// <seealso cref="Page.WaitForExpressionAsync(string, WaitForFunctionOptions)"/>304 /// <exception cref="WaitTaskTimeoutException">If timeout occurred.</exception>305 public Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options)306 => new WaitTask(this, script, true, "function", options.Polling, options.PollingInterval, options.Timeout).Task;307 /// <summary>308 /// Triggers a change and input event once all the provided options have been selected. 309 /// If there's no <![CDATA[<select>]]> element matching selector, the method throws an error.310 /// </summary>311 /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>312 /// <param name="selector">A selector to query page for</param>313 /// <param name="values">Values of options to select. If the <![CDATA[<select>]]> has the multiple attribute, 314 /// all values are considered, otherwise only the first one is taken into account.</param>315 /// <returns>Returns an array of option values that have been successfully selected.</returns>316 /// <seealso cref="Page.SelectAsync(string, string[])"/>317 public Task<string[]> SelectAsync(string selector, params string[] values)318 => QuerySelectorAsync(selector).EvaluateFunctionAsync<string[]>(@"(element, values) => {319 if (element.nodeName.toLowerCase() !== 'select')320 throw new Error('Element is not a <select> element.');321 const options = Array.from(element.options);322 element.value = undefined;323 for (const option of options) {324 option.selected = values.includes(option.value);325 if (option.selected && !element.multiple)326 break;327 }328 element.dispatchEvent(new Event('input', { 'bubbles': true }));329 element.dispatchEvent(new Event('change', { 'bubbles': true }));330 return options.filter(option => option.selected).map(option => option.value);331 }", new[] { values });332 /// <summary>333 /// Queries frame for the selector. If there's no such element within the frame, the method will resolve to <c>null</c>.334 /// </summary>335 /// <param name="selector">Selector to query frame for</param>336 /// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>337 /// <seealso cref="Page.QuerySelectorAsync(string)"/>338 public async Task<ElementHandle> QuerySelectorAsync(string selector)339 {340 var document = await GetDocument().ConfigureAwait(false);341 var value = await document.QuerySelectorAsync(selector).ConfigureAwait(false);342 return value;343 }344 /// <summary>345 /// Queries frame for the selector. If no elements match the selector, the return value resolve to <see cref="Array.Empty{T}"/>.346 /// </summary>347 /// <param name="selector">A selector to query frame for</param>348 /// <returns>Task which resolves to ElementHandles pointing to the frame elements</returns>349 /// <seealso cref="Page.QuerySelectorAllAsync(string)"/>350 public async Task<ElementHandle[]> QuerySelectorAllAsync(string selector)351 {352 var document = await GetDocument().ConfigureAwait(false);353 var value = await document.QuerySelectorAllAsync(selector).ConfigureAwait(false);354 return value;355 }356 /// <summary>357 /// Evaluates the XPath expression358 /// </summary>359 /// <param name="expression">Expression to evaluate <see href="https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"/></param>360 /// <returns>Task which resolves to an array of <see cref="ElementHandle"/></returns>361 /// <seealso cref="Page.XPathAsync(string)"/>362 public async Task<ElementHandle[]> XPathAsync(string expression)363 {364 var document = await GetDocument().ConfigureAwait(false);365 var value = await document.XPathAsync(expression).ConfigureAwait(false);366 return value;367 }368 /// <summary>369 /// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content370 /// </summary>371 /// <param name="options">add style tag options</param>372 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>373 /// <seealso cref="Page.AddStyleTagAsync(AddTagOptions)"/>374 /// <seealso cref="Page.AddStyleTagAsync(string)"/>375 public async Task<ElementHandle> AddStyleTag(AddTagOptions options)376 {377 const string addStyleUrl = @"async function addStyleUrl(url) {378 const link = document.createElement('link');379 link.rel = 'stylesheet';380 link.href = url;381 const promise = new Promise((res, rej) => {382 link.onload = res;383 link.onerror = rej;384 });385 document.head.appendChild(link);386 await promise;387 return link;388 }";389 const string addStyleContent = @"async function addStyleContent(content) {390 const style = document.createElement('style');391 style.type = 'text/css';392 style.appendChild(document.createTextNode(content));393 const promise = new Promise((res, rej) => {394 style.onload = res;395 style.onerror = rej;396 });397 document.head.appendChild(style);398 await promise;399 return style;400 }";401 if (!string.IsNullOrEmpty(options.Url))402 {403 var url = options.Url;404 try405 {406 var context = await GetExecutionContextAsync().ConfigureAwait(false);407 return (await context.EvaluateFunctionHandleAsync(addStyleUrl, url).ConfigureAwait(false)) as ElementHandle;408 }409 catch (PuppeteerException)410 {411 throw new PuppeteerException($"Loading style from {url} failed");412 }413 }414 if (!string.IsNullOrEmpty(options.Path))415 {416 var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);417 contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);418 var context = await GetExecutionContextAsync().ConfigureAwait(false);419 return (await context.EvaluateFunctionHandleAsync(addStyleContent, contents).ConfigureAwait(false)) as ElementHandle;420 }421 if (!string.IsNullOrEmpty(options.Content))422 {423 var context = await GetExecutionContextAsync().ConfigureAwait(false);424 return (await context.EvaluateFunctionHandleAsync(addStyleContent, options.Content).ConfigureAwait(false)) as ElementHandle;425 }426 throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");427 }428 /// <summary>429 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content430 /// </summary>431 /// <param name="options">add script tag options</param>432 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>433 /// <seealso cref="Page.AddScriptTagAsync(AddTagOptions)"/>434 /// <seealso cref="Page.AddScriptTagAsync(string)"/>435 public async Task<ElementHandle> AddScriptTag(AddTagOptions options)436 {437 const string addScriptUrl = @"async function addScriptUrl(url, type) {438 const script = document.createElement('script');439 script.src = url;440 if(type)441 script.type = type;442 const promise = new Promise((res, rej) => {443 script.onload = res;444 script.onerror = rej;445 });446 document.head.appendChild(script);447 await promise;448 return script;449 }";450 const string addScriptContent = @"function addScriptContent(content, type = 'text/javascript') {451 const script = document.createElement('script');452 script.type = type;453 script.text = content;454 let error = null;455 script.onerror = e => error = e;456 document.head.appendChild(script);457 if (error)458 throw error;459 return script;460 }";461 async Task<ElementHandle> AddScriptTagPrivate(string script, string urlOrContent, string type)462 {463 var context = await GetExecutionContextAsync().ConfigureAwait(false);464 return (string.IsNullOrEmpty(type)465 ? await context.EvaluateFunctionHandleAsync(script, urlOrContent).ConfigureAwait(false)466 : await context.EvaluateFunctionHandleAsync(script, urlOrContent, type).ConfigureAwait(false)) as ElementHandle;467 }468 if (!string.IsNullOrEmpty(options.Url))469 {470 var url = options.Url;471 try472 {473 return await AddScriptTagPrivate(addScriptUrl, url, options.Type).ConfigureAwait(false);474 }475 catch (PuppeteerException)476 {477 throw new PuppeteerException($"Loading script from {url} failed");478 }479 }480 if (!string.IsNullOrEmpty(options.Path))481 {482 var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);483 contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);484 return await AddScriptTagPrivate(addScriptContent, contents, options.Type).ConfigureAwait(false);485 }486 if (!string.IsNullOrEmpty(options.Content))487 {488 return await AddScriptTagPrivate(addScriptContent, options.Content, options.Type).ConfigureAwait(false);489 }490 throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");491 }492 /// <summary>493 /// Gets the full HTML contents of the page, including the doctype.494 /// </summary>495 /// <returns>Task which resolves to the HTML content.</returns>496 /// <seealso cref="Page.GetContentAsync"/>497 public Task<string> GetContentAsync()498 => EvaluateFunctionAsync<string>(@"() => {499 let retVal = '';500 if (document.doctype)501 retVal = new XMLSerializer().serializeToString(document.doctype);502 if (document.documentElement)503 retVal += document.documentElement.outerHTML;504 return retVal;505 }");506 /// <summary>507 /// Sets the HTML markup to the page508 /// </summary>509 /// <param name="html">HTML markup to assign to the page.</param>510 /// <returns>Task.</returns>511 /// <seealso cref="Page.SetContentAsync(string)"/>512 public Task SetContentAsync(string html)513 => EvaluateFunctionAsync(@"html => {514 document.open();515 document.write(html);516 document.close();517 }", html);518 /// <summary>519 /// Returns page's title520 /// </summary>521 /// <returns>page's title</returns>522 /// <seealso cref="Page.GetTitleAsync"/>523 public Task<string> GetTitleAsync() => EvaluateExpressionAsync<string>("document.title");524 internal async Task<ElementHandle> WaitForSelectorOrXPathAsync(string selectorOrXPath, bool isXPath, WaitForSelectorOptions options = null)525 {526 options = options ?? new WaitForSelectorOptions();527 const string predicate = @"528 function predicate(selectorOrXPath, isXPath, waitForVisible, waitForHidden) {529 const node = isXPath530 ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue531 : document.querySelector(selectorOrXPath);532 if (!node)533 return waitForHidden;534 if (!waitForVisible && !waitForHidden)535 return node;536 const element = node.nodeType === Node.TEXT_NODE ? node.parentElement : node;537 const style = window.getComputedStyle(element);538 const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();539 const success = (waitForVisible === isVisible || waitForHidden === !isVisible);540 return success ? node : null;541 function hasVisibleBoundingBox() {542 const rect = element.getBoundingClientRect();543 return !!(rect.top || rect.bottom || rect.width || rect.height);544 }545 }";546 var polling = options.Visible || options.Hidden ? WaitForFunctionPollingOption.Raf : WaitForFunctionPollingOption.Mutation;547 var handle = await new WaitTask(548 this,549 predicate,550 false,551 $"{(isXPath ? "XPath" : "selector")} '{selectorOrXPath}'{(options.Hidden ? " to be hidden" : "")}",552 options.Polling,553 options.PollingInterval,554 options.Timeout,555 new object[]556 {557 selectorOrXPath,558 isXPath,559 options.Visible,560 options.Hidden561 }).Task.ConfigureAwait(false);562 return handle as ElementHandle;563 }564 internal void OnLoadingStopped()565 {566 LifecycleEvents.Add("DOMContentLoaded");567 LifecycleEvents.Add("load");568 }569 internal void OnLifecycleEvent(string loaderId, string name)570 {571 if (name == "init")572 {573 LoaderId = loaderId;574 LifecycleEvents.Clear();575 }576 LifecycleEvents.Add(name);577 }578 internal void Navigated(FramePayload framePayload)579 {580 Name = framePayload.Name ?? string.Empty;581 NavigationURL = framePayload.Url;582 Url = framePayload.Url;583 }584 internal void NavigatedWithinDocument(string url) => Url = url;585 internal void SetDefaultContext(ExecutionContext context)586 {587 if (context != null)588 {589 _contextResolveTaskWrapper.SetResult(context);590 foreach (var waitTask in WaitTasks)591 {592 _ = waitTask.Rerun();593 }594 }595 else596 {597 _documentCompletionSource = null;598 _contextResolveTaskWrapper = new TaskCompletionSource<ExecutionContext>();599 }600 }601 internal void Detach()602 {603 while (WaitTasks.Count > 0)604 {605 WaitTasks[0].Terminate(new Exception("waitForFunction failed: frame got detached."));606 }607 Detached = true;608 if (ParentFrame != null)609 {610 ParentFrame.ChildFrames.Remove(this);611 }612 ParentFrame = null;613 }614 #endregion615 #region Private Methods616 private async Task<ElementHandle> GetDocument()617 {618 if (_documentCompletionSource == null)619 {620 _documentCompletionSource = new TaskCompletionSource<ElementHandle>();621 var context = await GetExecutionContextAsync().ConfigureAwait(false);622 var document = await context.EvaluateExpressionHandleAsync("document").ConfigureAwait(false);623 _documentCompletionSource.SetResult(document as ElementHandle);624 }625 return await _documentCompletionSource.Task.ConfigureAwait(false);626 }627 #endregion628 }629}...

Full Screen

Full Screen

PageEvaluateTests.cs

Source:PageEvaluateTests.cs Github

copy

Full Screen

...272 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should throw a nice error after a navigation")]273 [SkipBrowserFact(skipFirefox: true)]274 public async Task ShouldThrowANiceErrorAfterANavigation()275 {276 var executionContext = await Page.MainFrame.GetExecutionContextAsync();277 await Task.WhenAll(278 Page.WaitForNavigationAsync(),279 executionContext.EvaluateFunctionAsync("() => window.location.reload()")280 );281 var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>282 {283 return executionContext.EvaluateFunctionAsync("() => null");284 });285 Assert.Contains("navigation", ex.Message);286 }287 [PuppeteerTest("evaluation.spec.ts", "Page.evaluate", "should not throw an error when evaluation does a navigation")]288 [SkipBrowserFact(skipFirefox: true)]289 public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()290 {...

Full Screen

Full Screen

EvaluateTests.cs

Source:EvaluateTests.cs Github

copy

Full Screen

...232 }"));233 [Fact]234 public async Task ShouldThrowANiceErrorAfterANavigation()235 {236 var executionContext = await Page.MainFrame.GetExecutionContextAsync();237 await Task.WhenAll(238 Page.WaitForNavigationAsync(),239 executionContext.EvaluateFunctionAsync("() => window.location.reload()")240 );241 var ex = await Assert.ThrowsAsync<EvaluationFailedException>(() =>242 {243 return executionContext.EvaluateFunctionAsync("() => null");244 });245 Assert.Contains("navigation", ex.Message);246 }247 [Fact]248 public async Task ShouldNotThrowAnErrorWhenEvaluationDoesANavigation()249 {250 await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");...

Full Screen

Full Screen

DOMWorld.cs

Source:DOMWorld.cs Github

copy

Full Screen

...47 {48 WaitTasks[0].Terminate(new Exception("waitForFunction failed: frame got detached."));49 }50 }51 internal Task<ExecutionContext> GetExecutionContextAsync()52 {53 if (_detached)54 {55 throw new PuppeteerException($"Execution Context is not available in detached frame \"{Frame.Url}\"(are you trying to evaluate?)");56 }57 return _contextResolveTaskWrapper.Task;58 }59 internal async Task<JSHandle> EvaluateExpressionHandleAsync(string script)60 {61 var context = await GetExecutionContextAsync().ConfigureAwait(false);62 return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);63 }64 internal async Task<JSHandle> EvaluateFunctionHandleAsync(string script, params object[] args)65 {66 var context = await GetExecutionContextAsync().ConfigureAwait(false);67 return await context.EvaluateFunctionHandleAsync(script, args).ConfigureAwait(false);68 }69 internal async Task<T> EvaluateExpressionAsync<T>(string script)70 {71 var context = await GetExecutionContextAsync().ConfigureAwait(false);72 return await context.EvaluateExpressionAsync<T>(script).ConfigureAwait(false);73 }74 internal async Task<JToken> EvaluateExpressionAsync(string script)75 {76 var context = await GetExecutionContextAsync().ConfigureAwait(false);77 return await context.EvaluateExpressionAsync(script).ConfigureAwait(false);78 }79 internal async Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)80 {81 var context = await GetExecutionContextAsync().ConfigureAwait(false);82 return await context.EvaluateFunctionAsync<T>(script, args).ConfigureAwait(false);83 }84 internal async Task<JToken> EvaluateFunctionAsync(string script, params object[] args)85 {86 var context = await GetExecutionContextAsync().ConfigureAwait(false);87 return await context.EvaluateFunctionAsync(script, args).ConfigureAwait(false);88 }89 internal Task<string> GetContentAsync() => EvaluateFunctionAsync<string>(@"() => {90 let retVal = '';91 if (document.doctype)92 retVal = new XMLSerializer().serializeToString(document.doctype);93 if (document.documentElement)94 retVal += document.documentElement.outerHTML;95 return retVal;96 }");97 internal async Task SetContentAsync(string html, NavigationOptions options = null)98 {99 var waitUntil = options?.WaitUntil ?? new[] { WaitUntilNavigation.Load };100 var timeout = options?.Timeout ?? _timeoutSettings.NavigationTimeout;101 // We rely upon the fact that document.open() will reset frame lifecycle with "init"102 // lifecycle event. @see https://crrev.com/608658103 await EvaluateFunctionAsync(@"html => {104 document.open();105 document.write(html);106 document.close();107 }", html).ConfigureAwait(false);108 using (var watcher = new LifecycleWatcher(_frameManager, Frame, waitUntil, timeout))109 {110 var watcherTask = await Task.WhenAny(111 watcher.TimeoutOrTerminationTask,112 watcher.LifecycleTask).ConfigureAwait(false);113 await watcherTask.ConfigureAwait(false);114 }115 }116 internal async Task<ElementHandle> AddScriptTagAsync(AddTagOptions options)117 {118 const string addScriptUrl = @"async function addScriptUrl(url, type) {119 const script = document.createElement('script');120 script.src = url;121 if(type)122 script.type = type;123 const promise = new Promise((res, rej) => {124 script.onload = res;125 script.onerror = rej;126 });127 document.head.appendChild(script);128 await promise;129 return script;130 }";131 const string addScriptContent = @"function addScriptContent(content, type = 'text/javascript') {132 const script = document.createElement('script');133 script.type = type;134 script.text = content;135 let error = null;136 script.onerror = e => error = e;137 document.head.appendChild(script);138 if (error)139 throw error;140 return script;141 }";142 async Task<ElementHandle> AddScriptTagPrivate(string script, string urlOrContent, string type)143 {144 var context = await GetExecutionContextAsync().ConfigureAwait(false);145 return (string.IsNullOrEmpty(type)146 ? await context.EvaluateFunctionHandleAsync(script, urlOrContent).ConfigureAwait(false)147 : await context.EvaluateFunctionHandleAsync(script, urlOrContent, type).ConfigureAwait(false)) as ElementHandle;148 }149 if (!string.IsNullOrEmpty(options.Url))150 {151 var url = options.Url;152 try153 {154 return await AddScriptTagPrivate(addScriptUrl, url, options.Type).ConfigureAwait(false);155 }156 catch (PuppeteerException)157 {158 throw new PuppeteerException($"Loading script from {url} failed");159 }160 }161 if (!string.IsNullOrEmpty(options.Path))162 {163 var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);164 contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);165 return await AddScriptTagPrivate(addScriptContent, contents, options.Type).ConfigureAwait(false);166 }167 if (!string.IsNullOrEmpty(options.Content))168 {169 return await AddScriptTagPrivate(addScriptContent, options.Content, options.Type).ConfigureAwait(false);170 }171 throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");172 }173 internal async Task<ElementHandle> AddStyleTagAsync(AddTagOptions options)174 {175 const string addStyleUrl = @"async function addStyleUrl(url) {176 const link = document.createElement('link');177 link.rel = 'stylesheet';178 link.href = url;179 const promise = new Promise((res, rej) => {180 link.onload = res;181 link.onerror = rej;182 });183 document.head.appendChild(link);184 await promise;185 return link;186 }";187 const string addStyleContent = @"async function addStyleContent(content) {188 const style = document.createElement('style');189 style.type = 'text/css';190 style.appendChild(document.createTextNode(content));191 const promise = new Promise((res, rej) => {192 style.onload = res;193 style.onerror = rej;194 });195 document.head.appendChild(style);196 await promise;197 return style;198 }";199 if (!string.IsNullOrEmpty(options.Url))200 {201 var url = options.Url;202 try203 {204 var context = await GetExecutionContextAsync().ConfigureAwait(false);205 return (await context.EvaluateFunctionHandleAsync(addStyleUrl, url).ConfigureAwait(false)) as ElementHandle;206 }207 catch (PuppeteerException)208 {209 throw new PuppeteerException($"Loading style from {url} failed");210 }211 }212 if (!string.IsNullOrEmpty(options.Path))213 {214 var contents = await AsyncFileHelper.ReadAllText(options.Path).ConfigureAwait(false);215 contents += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);216 var context = await GetExecutionContextAsync().ConfigureAwait(false);217 return (await context.EvaluateFunctionHandleAsync(addStyleContent, contents).ConfigureAwait(false)) as ElementHandle;218 }219 if (!string.IsNullOrEmpty(options.Content))220 {221 var context = await GetExecutionContextAsync().ConfigureAwait(false);222 return (await context.EvaluateFunctionHandleAsync(addStyleContent, options.Content).ConfigureAwait(false)) as ElementHandle;223 }224 throw new ArgumentException("Provide options with a `Url`, `Path` or `Content` property");225 }226 internal Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)227 => WaitForSelectorOrXPathAsync(selector, false, options);228 internal Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)229 => WaitForSelectorOrXPathAsync(xpath, true, options);230 internal Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)231 => new WaitTask(232 this,233 script,234 false,235 "function",236 options.Polling,237 options.PollingInterval,238 options.Timeout ?? _timeoutSettings.Timeout,239 args).Task;240 internal Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options)241 => new WaitTask(242 this,243 script,244 true,245 "function",246 options.Polling,247 options.PollingInterval,248 options.Timeout ?? _timeoutSettings.Timeout).Task;249 internal Task<string> GetTitleAsync() => EvaluateExpressionAsync<string>("document.title");250 private async Task<ElementHandle> GetDocument()251 {252 if (_documentCompletionSource == null)253 {254 _documentCompletionSource = new TaskCompletionSource<ElementHandle>(TaskCreationOptions.RunContinuationsAsynchronously);255 var context = await GetExecutionContextAsync().ConfigureAwait(false);256 var document = await context.EvaluateExpressionHandleAsync("document").ConfigureAwait(false);257 _documentCompletionSource.TrySetResult(document as ElementHandle);258 }259 return await _documentCompletionSource.Task.ConfigureAwait(false);260 }261 private async Task<ElementHandle> WaitForSelectorOrXPathAsync(string selectorOrXPath, bool isXPath, WaitForSelectorOptions options = null)262 {263 options = options ?? new WaitForSelectorOptions();264 var timeout = options.Timeout ?? _timeoutSettings.Timeout;265 const string predicate = @"266 function predicate(selectorOrXPath, isXPath, waitForVisible, waitForHidden) {267 const node = isXPath268 ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue269 : document.querySelector(selectorOrXPath);...

Full Screen

Full Screen

WaitTask.cs

Source:WaitTask.cs Github

copy

Full Screen

...139 {140 var runCount = Interlocked.Increment(ref _runCount);141 JSHandle success = null;142 Exception exception = null;143 var context = await _frame.GetExecutionContextAsync().ConfigureAwait(false);144 try145 {146 success = await context.EvaluateFunctionHandleAsync(WaitForPredicatePageFunction,147 new object[] { _predicateBody, _pollingInterval ?? (object)_polling, _timeout }.Concat(_args).ToArray()).ConfigureAwait(false);148 }149 catch (Exception ex)150 {151 exception = ex;152 }153 if (_terminated || runCount != _runCount)154 {155 if (success != null)156 {157 await success.DisposeAsync().ConfigureAwait(false);...

Full Screen

Full Screen

ExecutionContextTests.cs

Source:ExecutionContextTests.cs Github

copy

Full Screen

...14 {15 await Page.GoToAsync(TestConstants.EmptyPage);16 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);17 Assert.Equal(2, Page.Frames.Length);18 var context1 = await Page.MainFrame.GetExecutionContextAsync();19 var context2 = await Page.FirstChildFrame().GetExecutionContextAsync();20 Assert.NotNull(context1);21 Assert.NotNull(context2);22 Assert.NotEqual(context1, context2);23 Assert.Equal(Page.MainFrame, context1.Frame);24 Assert.Equal(Page.FirstChildFrame(), context2.Frame);25 await Task.WhenAll(26 context1.EvaluateExpressionAsync("window.a = 1"),27 context2.EvaluateExpressionAsync("window.a = 2")28 );29 var a1 = context1.EvaluateExpressionAsync<int>("window.a");30 var a2 = context2.EvaluateExpressionAsync<int>("window.a");31 await Task.WhenAll(a1, a2);32 Assert.Equal(1, a1.Result);33 Assert.Equal(2, a2.Result);...

Full Screen

Full Screen

ContextTests.cs

Source:ContextTests.cs Github

copy

Full Screen

...14 {15 await Page.GoToAsync(TestConstants.EmptyPage);16 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);17 Assert.Equal(2, Page.Frames.Length);18 var context1 = await Page.Frames[0].GetExecutionContextAsync();19 var context2 = await Page.Frames[1].GetExecutionContextAsync();20 Assert.NotNull(context1);21 Assert.NotNull(context2);22 Assert.NotEqual(context1, context2);23 await Task.WhenAll(24 context1.EvaluateExpressionAsync("window.a = 1"),25 context2.EvaluateExpressionAsync("window.a = 2")26 );27 var a1 = context1.EvaluateExpressionAsync<int>("window.a");28 var a2 = context2.EvaluateExpressionAsync<int>("window.a");29 await Task.WhenAll(a1, a2);30 Assert.Equal(1, a1.Result);31 Assert.Equal(2, a2.Result);32 }33 }...

Full Screen

Full Screen

GetExecutionContextAsync

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 LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 var context = await page.GetExecutionContextAsync();14 var result = await context.EvaluateFunctionAsync<string>("() => { return \"Hello world!\"; }");15 Console.WriteLine(result);16 await browser.CloseAsync();17 }18 }19}

Full Screen

Full Screen

GetExecutionContextAsync

Using AI Code Generation

copy

Full Screen

1var frame = await page.GetMainFrameAsync();2var context = await frame.GetExecutionContextAsync();3var context = await page.GetExecutionContextAsync();4var context = await elementHandle.GetExecutionContextAsync();5var frame = await page.GetMainFrameAsync();6var context = await frame.GetExecutionContextAsync();7var context = await page.GetExecutionContextAsync();8var context = await elementHandle.GetExecutionContextAsync();9var frame = await page.GetMainFrameAsync();10var context = await frame.GetExecutionContextAsync();11var context = await page.GetExecutionContextAsync();12var context = await elementHandle.GetExecutionContextAsync();13var frame = await page.GetMainFrameAsync();14var context = await frame.GetExecutionContextAsync();15var context = await page.GetExecutionContextAsync();16var context = await elementHandle.GetExecutionContextAsync();17var frame = await page.GetMainFrameAsync();18var context = await frame.GetExecutionContextAsync();19var context = await page.GetExecutionContextAsync();20var context = await elementHandle.GetExecutionContextAsync();21var frame = await page.GetMainFrameAsync();22var context = await frame.GetExecutionContextAsync();23var context = await page.GetExecutionContextAsync();

Full Screen

Full Screen

GetExecutionContextAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2var frame = await page.GetMainFrameAsync();3var context = await frame.GetExecutionContextAsync();4var result = await context.EvaluateFunctionAsync<int>("() => 7 * 3");5var page = await browser.NewPageAsync();6var frame = await page.GetMainFrameAsync();7var context = await frame.GetExecutionContextAsync();8var result = await context.EvaluateFunctionAsync<int>("() => 7 * 3");9var page = await browser.NewPageAsync();10var frame = await page.GetMainFrameAsync();11var context = await frame.GetExecutionContextAsync();12var result = await context.EvaluateFunctionAsync<int>("() => 7 * 3");13var page = await browser.NewPageAsync();14var frame = await page.GetMainFrameAsync();15var context = await frame.GetExecutionContextAsync();16var result = await context.EvaluateFunctionAsync<int>("() => 7 * 3");17var page = await browser.NewPageAsync();18var frame = await page.GetMainFrameAsync();19var context = await frame.GetExecutionContextAsync();20var result = await context.EvaluateFunctionAsync<int>("() => 7 * 3");21var page = await browser.NewPageAsync();22var frame = await page.GetMainFrameAsync();23var context = await frame.GetExecutionContextAsync();24var result = await context.EvaluateFunctionAsync<int>("() => 7 * 3");

Full Screen

Full Screen

GetExecutionContextAsync

Using AI Code Generation

copy

Full Screen

1var executionContext = await frame.GetExecutionContextAsync();2var result = await executionContext.EvaluateFunctionAsync<int>("() => 7 * 3");3var executionContext = await page.GetExecutionContextAsync();4var result = await executionContext.EvaluateFunctionAsync<int>("() => 7 * 3");5var executionContext = await frame.GetExecutionContextAsync();6var result = await executionContext.EvaluateExpressionAsync<int>("7 * 3");7var executionContext = await page.GetExecutionContextAsync();8var result = await executionContext.EvaluateExpressionAsync<int>("7 * 3");9var executionContext = await frame.GetExecutionContextAsync();10var result = await executionContext.EvaluateFunctionHandleAsync("() => document.body");11var executionContext = await page.GetExecutionContextAsync();12var result = await executionContext.EvaluateFunctionHandleAsync("() => document.body");13var executionContext = await frame.GetExecutionContextAsync();14var result = await executionContext.EvaluateExpressionHandleAsync("document.body");15var executionContext = await page.GetExecutionContextAsync();16var result = await executionContext.EvaluateExpressionHandleAsync("document.body");17var executionContext = await frame.GetExecutionContextAsync();18var result = await executionContext.EvaluateAsync("() => 7 * 3");

Full Screen

Full Screen

GetExecutionContextAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2var frame = page.MainFrame;3var context = await frame.GetExecutionContextAsync();4var result = await context.EvaluateExpressionAsync<int>("document.body.childElementCount");5Console.WriteLine(result);6var page = await browser.NewPageAsync();7var frame = page.MainFrame;8var context = await frame.GetExecutionContextAsync();9var result = await context.EvaluateExpressionAsync<int>("document.body.childElementCount");10Console.WriteLine(result);11var page = await browser.NewPageAsync();12var frame = page.MainFrame;13var context = await frame.GetExecutionContextAsync();14var result = await context.EvaluateExpressionAsync<int>("document.body.childElementCount");15Console.WriteLine(result);16var page = await browser.NewPageAsync();17var frame = page.MainFrame;18var context = await frame.GetExecutionContextAsync();19var result = await context.EvaluateExpressionAsync<int>("document.body.childElementCount");20Console.WriteLine(result);21var page = await browser.NewPageAsync();22var frame = page.MainFrame;23var context = await frame.GetExecutionContextAsync();24var result = await context.EvaluateExpressionAsync<int>("document.body.childElementCount");25Console.WriteLine(result);26var page = await browser.NewPageAsync();

Full Screen

Full Screen

GetExecutionContextAsync

Using AI Code Generation

copy

Full Screen

1var frame = await page.GetMainFrameAsync();2var context = await frame.GetExecutionContextAsync();3var result = await context.EvaluateFunctionAsync<int>("() => 8 * 7");4var frame = await page.GetMainFrameAsync();5var context = await frame.GetExecutionContextAsync();6var result = await context.EvaluateFunctionAsync<int>("() => 8 * 7");7var frame = await page.GetMainFrameAsync();8var context = await frame.GetExecutionContextAsync();9var result = await context.EvaluateFunctionAsync<int>("() => 8 * 7");10var frame = await page.GetMainFrameAsync();11var context = await frame.GetExecutionContextAsync();12var result = await context.EvaluateFunctionAsync<int>("() => 8 * 7");13var frame = await page.GetMainFrameAsync();14var context = await frame.GetExecutionContextAsync();15var result = await context.EvaluateFunctionAsync<int>("() => 8 * 7");16var frame = await page.GetMainFrameAsync();17var context = await frame.GetExecutionContextAsync();18var result = await context.EvaluateFunctionAsync<int>("() => 8 * 7");19var frame = await page.GetMainFrameAsync();20var context = await frame.GetExecutionContextAsync();21var result = await context.EvaluateFunctionAsync<int>("() => 8 * 7");22var frame = await page.GetMainFrameAsync();23var context = await frame.GetExecutionContextAsync();24var result = await context.EvaluateFunctionAsync<int>("()

Full Screen

Full Screen

GetExecutionContextAsync

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 executionContext = await page.GetExecutionContextAsync();13 var result = await executionContext.EvaluateExpressionAsync<int>("1+1");14 Console.WriteLine(result);15 }16 }17 }18}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful