How to use FrameManager method of PuppeteerSharp.FrameManager class

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

Page.cs

Source:Page.cs Github

copy

Full Screen

...219 /// </summary>220 /// <remarks>221 /// Page is guaranteed to have a main frame which persists during navigations.222 /// </remarks>223 public Frame MainFrame => FrameManager.MainFrame;224 /// <summary>225 /// Gets all frames attached to the page.226 /// </summary>227 /// <value>An array of all frames attached to the page.</value>228 public Frame[] Frames => FrameManager.GetFrames();229 ///// <summary>230 ///// Gets all workers in the page.231 ///// </summary>232 //public Worker[] Workers => _workers.Values.ToArray();233 /// <summary>234 /// Shortcut for <c>page.MainFrame.Url</c>235 /// </summary>236 public string Url => MainFrame.Url;237 /// <summary>238 /// Gets that target this page was created from.239 /// </summary>240 public Target Target { get; }241 /// <summary>242 /// Gets this page's keyboard243 /// </summary>244 public Keyboard Keyboard { get; }245 /// <summary>246 /// Gets this page's touchscreen247 /// </summary>248 public Touchscreen Touchscreen { get; }249 /// <summary>250 /// Gets this page's coverage251 /// </summary>252 public Coverage Coverage { get; }253 /// <summary>254 /// Gets this page's mouse255 /// </summary>256 public Mouse Mouse { get; }257 /// <summary>258 /// Gets this page's viewport259 /// </summary>260 public ViewPortOptions Viewport { get; private set; }261 /// <summary>262 /// List of supported metrics provided by the <see cref="Metrics"/> event.263 /// </summary>264 public static readonly IEnumerable<string> SupportedMetrics = new List<string>265 {266 "Timestamp",267 "Documents",268 "Frames",269 "JSEventListeners",270 "Nodes",271 "LayoutCount",272 "RecalcStyleCount",273 "LayoutDuration",274 "RecalcStyleDuration",275 "ScriptDuration",276 "TaskDuration",277 "JSHeapUsedSize",278 "JSHeapTotalSize"279 };280 /// <summary>281 /// Get the browser the page belongs to.282 /// </summary>283 public Browser Browser => Target.Browser;284 /// <summary>285 /// Get the browser context that the page belongs to.286 /// </summary>287 public BrowserContext BrowserContext => Target.BrowserContext;288 /// <summary>289 /// Get an indication that the page has been closed.290 /// </summary>291 public bool IsClosed { get; private set; }292 /// <summary>293 /// Gets the accessibility.294 /// </summary>295 public Accessibility Accessibility { get; }296 internal bool JavascriptEnabled { get; set; } = true;297 internal bool HasPopupEventListeners => Popup?.GetInvocationList().Any() == true;298 internal FrameManager FrameManager { get; private set; }299 private Task SessionClosedTask300 {301 get302 {303 if (_sessionClosedTcs == null)304 {305 _sessionClosedTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);306 Client.Disconnected += clientDisconnected;307 void clientDisconnected(object sender, EventArgs e)308 {309 _sessionClosedTcs.TrySetException(new TargetClosedException("Target closed", "Session closed"));310 Client.Disconnected -= clientDisconnected;311 }312 }313 return _sessionClosedTcs.Task;314 }315 }316 #endregion317 #region Public Methods318 /// <summary>319 /// A utility function to be used with <see cref="Extensions.EvaluateFunctionAsync{T}(Task{JSHandle}, string, object[])"/>320 /// </summary>321 /// <param name="selector">A selector to query page for</param>322 /// <returns>Task which resolves to a <see cref="JSHandle"/> of <c>document.querySelectorAll</c> result</returns>323 public Task<JSHandle> QuerySelectorAllHandleAsync(string selector)324 => EvaluateFunctionHandleAsync("selector => Array.from(document.querySelectorAll(selector))", selector);325 /// <summary>326 /// Executes a script in browser context327 /// </summary>328 /// <param name="script">Script to be evaluated in browser context</param>329 /// <remarks>330 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.331 /// </remarks>332 /// <returns>Task which resolves to script return value</returns>333 public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)334 {335 var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);336 return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);337 }338 /// <summary>339 /// Executes a script in browser context340 /// </summary>341 /// <param name="pageFunction">Script to be evaluated in browser context</param>342 /// <param name="args">Function arguments</param>343 /// <remarks>344 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.345 /// <see cref="JSHandle"/> instances can be passed as arguments346 /// </remarks>347 /// <returns>Task which resolves to script return value</returns>348 public async Task<JSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)349 {350 var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);351 return await context.EvaluateFunctionHandleAsync(pageFunction, args).ConfigureAwait(false);352 }353 /// <summary>354 /// Activating request interception enables <see cref="Request.AbortAsync(RequestAbortErrorCode)">request.AbortAsync</see>, 355 /// <see cref="Request.ContinueAsync(Payload)">request.ContinueAsync</see> and <see cref="Request.RespondAsync(ResponseData)">request.RespondAsync</see> methods.356 /// </summary>357 /// <returns>The request interception task.</returns>358 /// <param name="value">Whether to enable request interception..</param>359 public Task SetRequestInterceptionAsync(bool value)360 => FrameManager.NetworkManager.SetRequestInterceptionAsync(value);361 /// <summary>362 /// Set offline mode for the page.363 /// </summary>364 /// <returns>Result task</returns>365 /// <param name="value">When <c>true</c> enables offline mode for the page.</param>366 public Task SetOfflineModeAsync(bool value) => FrameManager.NetworkManager.SetOfflineModeAsync(value);367 /// <summary>368 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content369 /// </summary>370 /// <param name="options">add script tag options</param>371 /// <remarks>372 /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(options)</c>373 /// </remarks>374 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>375 /// <seealso cref="Frame.AddScriptTagAsync(AddTagOptions)"/>376 public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options) => MainFrame.AddScriptTagAsync(options);377 /// <summary>378 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content379 /// </summary>380 /// <param name="url">script url</param>381 /// <remarks>382 /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(new AddTagOptions { Url = url })</c>383 /// </remarks>384 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>385 public Task<ElementHandle> AddScriptTagAsync(string url) => AddScriptTagAsync(new AddTagOptions { Url = url });386 /// <summary>387 /// 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 content388 /// </summary>389 /// <param name="options">add style tag options</param>390 /// <remarks>391 /// Shortcut for <c>page.MainFrame.AddStyleTagAsync(options)</c>392 /// </remarks>393 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>394 /// <seealso cref="Frame.AddStyleTag(AddTagOptions)"/>395 public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options) => MainFrame.AddStyleTagAsync(options);396 /// <summary>397 /// 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 content398 /// </summary>399 /// <param name="url">stylesheel url</param>400 /// <remarks>401 /// Shortcut for <c>page.MainFrame.AddStyleTagAsync(new AddTagOptions { Url = url })</c>402 /// </remarks>403 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>404 public Task<ElementHandle> AddStyleTagAsync(string url) => AddStyleTagAsync(new AddTagOptions { Url = url });405 /// <summary>406 /// Adds a function called <c>name</c> on the page's <c>window</c> object.407 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves when <paramref name="puppeteerFunction"/> completes.408 /// </summary>409 /// <param name="name">Name of the function on the window object</param>410 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>411 /// <remarks>412 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.413 /// Functions installed via <see cref="ExposeFunctionAsync(string, Action)"/> survive navigations414 /// </remarks>415 /// <returns>Task</returns>416 public Task ExposeFunctionAsync(string name, Action puppeteerFunction)417 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);418 /// <summary>419 /// Adds a function called <c>name</c> on the page's <c>window</c> object.420 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.421 /// </summary>422 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>423 /// <param name="name">Name of the function on the window object</param>424 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>425 /// <remarks>426 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.427 /// Functions installed via <see cref="ExposeFunctionAsync{TResult}(string, Func{TResult})"/> survive navigations428 /// </remarks>429 /// <returns>Task</returns>430 public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> puppeteerFunction)431 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);432 /// <summary>433 /// Adds a function called <c>name</c> on the page's <c>window</c> object.434 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.435 /// </summary>436 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>437 /// <typeparam name="T">The parameter of <paramref name="puppeteerFunction"/></typeparam>438 /// <param name="name">Name of the function on the window object</param>439 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>440 /// <remarks>441 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.442 /// Functions installed via <see cref="ExposeFunctionAsync{T, TResult}(string, Func{T, TResult})"/> survive navigations443 /// </remarks>444 /// <returns>Task</returns>445 public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> puppeteerFunction)446 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);447 /// <summary>448 /// Adds a function called <c>name</c> on the page's <c>window</c> object.449 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.450 /// </summary>451 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>452 /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>453 /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>454 /// <param name="name">Name of the function on the window object</param>455 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>456 /// <remarks>457 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.458 /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, TResult}(string, Func{T1, T2, TResult})"/> survive navigations459 /// </remarks>460 /// <returns>Task</returns>461 public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> puppeteerFunction)462 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);463 /// <summary>464 /// Adds a function called <c>name</c> on the page's <c>window</c> object.465 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.466 /// </summary>467 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>468 /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>469 /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>470 /// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>471 /// <param name="name">Name of the function on the window object</param>472 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>473 /// <remarks>474 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.475 /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, TResult}(string, Func{T1, T2, T3, TResult})"/> survive navigations476 /// </remarks>477 /// <returns>Task</returns>478 public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> puppeteerFunction)479 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);480 /// <summary>481 /// Adds a function called <c>name</c> on the page's <c>window</c> object.482 /// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.483 /// </summary>484 /// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>485 /// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>486 /// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>487 /// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>488 /// <typeparam name="T4">The fourth parameter of <paramref name="puppeteerFunction"/></typeparam>489 /// <param name="name">Name of the function on the window object</param>490 /// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>491 /// <remarks>492 /// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.493 /// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, T4, TResult}(string, Func{T1, T2, T3, T4, TResult})"/> survive navigations494 /// </remarks>495 /// <returns>Task</returns>496 public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> puppeteerFunction)497 => ExposeFunctionAsync(name, (Delegate)puppeteerFunction);498 /// <summary>499 /// Gets the full HTML contents of the page, including the doctype.500 /// </summary>501 /// <returns>Task which resolves to the HTML content.</returns>502 /// <seealso cref="Frame.GetContentAsync"/>503 public Task<string> GetContentAsync() => FrameManager.MainFrame.GetContentAsync();504 /// <summary>505 /// Sets the HTML markup to the page506 /// </summary>507 /// <param name="html">HTML markup to assign to the page.</param>508 /// <param name="options">The navigations options</param>509 /// <returns>Task.</returns>510 /// <seealso cref="Frame.SetContentAsync(string, NavigationOptions)"/>511 public Task SetContentAsync(string html, NavigationOptions options = null) => FrameManager.MainFrame.SetContentAsync(html, options);512 /// <summary>513 /// Navigates to an url514 /// </summary>515 /// <remarks>516 /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will throw an error if:517 /// - there's an SSL error (e.g. in case of self-signed certificates).518 /// - target URL is invalid.519 /// - the `timeout` is exceeded during navigation.520 /// - the remote server does not respond or is unreachable.521 /// - the main resource failed to load.522 /// 523 /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will not throw an error when any valid HTTP status code is returned by the remote server, 524 /// including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling <see cref="Response.Status"/>525 /// 526 /// > **NOTE** <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> either throws an error or returns a main resource response. 527 /// The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.528 /// 529 /// > **NOTE** Headless mode doesn't support navigation to a PDF document. See the <see fref="https://bugs.chromium.org/p/chromium/issues/detail?id=761295">upstream issue</see>.530 /// 531 /// Shortcut for <seealso cref="Frame.GoToAsync(string, int?, WaitUntilNavigation[])"/>532 /// </remarks>533 /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>534 /// <param name="options">Navigation parameters.</param>535 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.</returns>536 /// <seealso cref="GoToAsync(string, int?, WaitUntilNavigation[])"/>537 public Task<Response> GoToAsync(string url, NavigationOptions options) => FrameManager.MainFrame.GoToAsync(url, options);538 /// <summary>539 /// Navigates to an url540 /// </summary>541 /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>542 /// <param name="timeout">Maximum navigation time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout. </param>543 /// <param name="waitUntil">When to consider navigation succeeded, defaults to <see cref="WaitUntilNavigation.Load"/>. Given an array of <see cref="WaitUntilNavigation"/>, navigation is considered to be successful after all events have been fired</param>544 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>545 /// <seealso cref="GoToAsync(string, NavigationOptions)"/>546 public Task<Response> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)547 => GoToAsync(url, new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });548 /// <summary>549 /// Navigates to an url550 /// </summary>551 /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>552 /// <param name="waitUntil">When to consider navigation succeeded.</param>553 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>554 /// <seealso cref="GoToAsync(string, NavigationOptions)"/>555 public Task<Response> GoToAsync(string url, WaitUntilNavigation waitUntil)556 => GoToAsync(url, new NavigationOptions { WaitUntil = new[] { waitUntil } });557 /// <summary>558 /// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>559 /// </summary>560 /// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>561 /// <returns></returns>562 /// <remarks>563 /// Generating a pdf is currently only supported in Chrome headless564 /// </remarks>565 public Task PdfAsync(string file) => PdfAsync(file, new PdfOptions());566 /// <summary>567 /// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>568 /// </summary>569 /// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>570 /// <param name="options">pdf options</param>571 /// <returns></returns>572 /// <remarks>573 /// Generating a pdf is currently only supported in Chrome headless574 /// </remarks>575 public async Task PdfAsync(string file, PdfOptions options)576 => await PdfInternalAsync(file, options).ConfigureAwait(false);577 /// <summary>578 /// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>579 /// </summary>580 /// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>581 /// <remarks>582 /// Generating a pdf is currently only supported in Chrome headless583 /// </remarks>584 public Task<Stream> PdfStreamAsync() => PdfStreamAsync(new PdfOptions());585 /// <summary>586 /// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>587 /// </summary>588 /// <param name="options">pdf options</param>589 /// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>590 /// <remarks>591 /// Generating a pdf is currently only supported in Chrome headless592 /// </remarks>593 public async Task<Stream> PdfStreamAsync(PdfOptions options)594 => new MemoryStream(await PdfDataAsync(options).ConfigureAwait(false));595 /// <summary>596 /// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>597 /// </summary>598 /// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>599 /// <remarks>600 /// Generating a pdf is currently only supported in Chrome headless601 /// </remarks>602 public Task<byte[]> PdfDataAsync() => PdfDataAsync(new PdfOptions());603 /// <summary>604 /// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>605 /// </summary>606 /// <param name="options">pdf options</param>607 /// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>608 /// <remarks>609 /// Generating a pdf is currently only supported in Chrome headless610 /// </remarks>611 public Task<byte[]> PdfDataAsync(PdfOptions options) => PdfInternalAsync(null, options);612 internal async Task<byte[]> PdfInternalAsync(string file, PdfOptions options)613 {614 var paperWidth = PaperFormat.Letter.Width;615 var paperHeight = PaperFormat.Letter.Height;616 if (options.Format != null)617 {618 paperWidth = options.Format.Width;619 paperHeight = options.Format.Height;620 }621 else622 {623 if (options.Width != null)624 {625 paperWidth = ConvertPrintParameterToInches(options.Width);626 }627 if (options.Height != null)628 {629 paperHeight = ConvertPrintParameterToInches(options.Height);630 }631 }632 var marginTop = ConvertPrintParameterToInches(options.MarginOptions.Top);633 var marginLeft = ConvertPrintParameterToInches(options.MarginOptions.Left);634 var marginBottom = ConvertPrintParameterToInches(options.MarginOptions.Bottom);635 var marginRight = ConvertPrintParameterToInches(options.MarginOptions.Right);636 var result = await Client.SendAsync<PagePrintToPDFResponse>("Page.printToPDF", new PagePrintToPDFRequest637 {638 TransferMode = "ReturnAsStream",639 Landscape = options.Landscape,640 DisplayHeaderFooter = options.DisplayHeaderFooter,641 HeaderTemplate = options.HeaderTemplate,642 FooterTemplate = options.FooterTemplate,643 PrintBackground = options.PrintBackground,644 Scale = options.Scale,645 PaperWidth = paperWidth,646 PaperHeight = paperHeight,647 MarginTop = marginTop,648 MarginBottom = marginBottom,649 MarginLeft = marginLeft,650 MarginRight = marginRight,651 PageRanges = options.PageRanges,652 PreferCSSPageSize = options.PreferCSSPageSize653 }).ConfigureAwait(false);654 return await ProtocolStreamReader.ReadProtocolStreamByteAsync(Client, result.Stream, file).ConfigureAwait(false);655 }656 /// <summary>657 /// Enables/Disables Javascript on the page658 /// </summary>659 /// <returns>Task.</returns>660 /// <param name="enabled">Whether or not to enable JavaScript on the page.</param>661 public Task SetJavaScriptEnabledAsync(bool enabled)662 {663 if (enabled == JavascriptEnabled)664 {665 return Task.CompletedTask;666 }667 JavascriptEnabled = enabled;668 return Client.SendAsync("Emulation.setScriptExecutionDisabled", new EmulationSetScriptExecutionDisabledRequest669 {670 Value = !enabled671 });672 }673 /// <summary>674 /// Toggles bypassing page's Content-Security-Policy.675 /// </summary>676 /// <param name="enabled">sets bypassing of page's Content-Security-Policy.</param>677 /// <returns></returns>678 /// <remarks>679 /// CSP bypassing happens at the moment of CSP initialization rather then evaluation.680 /// Usually this means that <see cref="SetBypassCSPAsync(bool)"/> should be called before navigating to the domain.681 /// </remarks>682 public Task SetBypassCSPAsync(bool enabled) => Client.SendAsync("Page.setBypassCSP", new PageSetBypassCSPRequest683 {684 Enabled = enabled685 });686 /// <summary>687 /// Emulates a media such as screen or print.688 /// </summary>689 /// <returns>Task.</returns>690 /// <param name="media">Media to set.</param>691 [Obsolete("User EmulateMediaTypeAsync instead")]692 public Task EmulateMediaAsync(MediaType media) => EmulateMediaTypeAsync(media);693 /// <summary>694 /// Emulates a media such as screen or print.695 /// </summary>696 /// <param name="type">Media to set.</param>697 /// <example>698 /// <code>699 /// <![CDATA[700 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");701 /// // → true702 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");703 /// // → true704 /// await page.EmulateMediaTypeAsync(MediaType.Print);705 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");706 /// // → false707 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");708 /// // → true709 /// await page.EmulateMediaTypeAsync(MediaType.None);710 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");711 /// // → true712 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");713 /// // → true714 /// ]]>715 /// </code>716 /// </example>717 /// <returns>Emulate media type task.</returns>718 public Task EmulateMediaTypeAsync(MediaType type)719 => Client.SendAsync("Emulation.setEmulatedMedia", new EmulationSetEmulatedMediaTypeRequest { Media = type });720 /// <summary>721 /// Given an array of media feature objects, emulates CSS media features on the page.722 /// </summary>723 /// <param name="features">Features to apply</param>724 /// <example>725 /// <code>726 /// <![CDATA[727 /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" }});728 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");729 /// // → true730 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");731 /// // → false732 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");733 /// // → false734 /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" }});735 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");736 /// // → true737 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");738 /// // → false739 /// await page.EmulateMediaFeaturesAsync(new MediaFeature[]740 /// { 741 /// new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" },742 /// new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" },743 /// });744 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");745 /// // → true746 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");747 /// // → false748 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");749 /// // → false750 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");751 /// // → true752 /// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");753 /// // → false754 /// ]]>755 /// </code>756 /// </example>757 /// <returns>Emulate features task</returns>758 public Task EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue> features)759 => Client.SendAsync("Emulation.setEmulatedMedia", new EmulationSetEmulatedMediaFeatureRequest { Features = features });760 /// <summary>761 /// Sets the viewport.762 /// In the case of multiple pages in a single browser, each page can have its own viewport size.763 /// <see cref="SetViewportAsync(ViewPortOptions)"/> will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.764 /// </summary>765 /// <example>766 ///<![CDATA[767 /// using(var page = await browser.NewPageAsync())768 /// {769 /// await page.SetViewPortAsync(new ViewPortOptions770 /// {771 /// Width = 640, 772 /// Height = 480, 773 /// DeviceScaleFactor = 1774 /// });775 /// await page.goto('https://www.example.com');776 /// }777 /// ]]>778 /// </example>779 /// <returns>The viewport task.</returns>780 /// <param name="viewport">Viewport options.</param>781 public async Task SetViewportAsync(ViewPortOptions viewport)782 {783 var needsReload = await _emulationManager.EmulateViewport(viewport).ConfigureAwait(false);784 Viewport = viewport;785 if (needsReload)786 {787 await ReloadAsync().ConfigureAwait(false);788 }789 }790 /// <summary>791 /// Closes the page.792 /// </summary>793 /// <param name="options">Close options.</param>794 /// <returns>Task.</returns>795 public Task CloseAsync(PageCloseOptions options = null)796 {797 if (!(Client?.Connection?.IsClosed ?? true))798 {799 var runBeforeUnload = options?.RunBeforeUnload ?? false;800 if (runBeforeUnload)801 {802 return Client.SendAsync("Page.close");803 }804 return Client.Connection.SendAsync("Target.closeTarget", new TargetCloseTargetRequest805 {806 TargetId = Target.TargetId807 }).ContinueWith(task => Target.CloseTask);808 }809 return _closeCompletedTcs.Task;810 }811 /// <summary>812 /// Reloads the page813 /// </summary>814 /// <param name="options">Navigation options</param>815 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>816 /// <seealso cref="ReloadAsync(int?, WaitUntilNavigation[])"/>817 public async Task<Response> ReloadAsync(NavigationOptions options)818 {819 var navigationTask = WaitForNavigationAsync(options);820 await Task.WhenAll(821 navigationTask,822 Client.SendAsync("Page.reload")823 ).ConfigureAwait(false);824 return navigationTask.Result;825 }826 /// <summary>827 /// Reloads the page828 /// </summary>829 /// <param name="timeout">Maximum navigation time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout. </param>830 /// <param name="waitUntil">When to consider navigation succeeded, defaults to <see cref="WaitUntilNavigation.Load"/>. Given an array of <see cref="WaitUntilNavigation"/>, navigation is considered to be successful after all events have been fired</param>831 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>832 /// <seealso cref="ReloadAsync(NavigationOptions)"/>833 public Task<Response> ReloadAsync(int? timeout = null, WaitUntilNavigation[] waitUntil = null)834 => ReloadAsync(new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });835 /// <summary>836 /// Waits for a function to be evaluated to a truthy value837 /// </summary>838 /// <param name="script">Function to be evaluated in browser context</param>839 /// <param name="options">Optional waiting parameters</param>840 /// <param name="args">Arguments to pass to <c>script</c></param>841 /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>842 /// <seealso cref="Frame.WaitForFunctionAsync(string, WaitForFunctionOptions, object[])"/>843 public Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options = null, params object[] args)844 => MainFrame.WaitForFunctionAsync(script, options ?? new WaitForFunctionOptions(), args);845 /// <summary>846 /// Waits for an expression to be evaluated to a truthy value847 /// </summary>848 /// <param name="script">Expression to be evaluated in browser context</param>849 /// <param name="options">Optional waiting parameters</param>850 /// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>851 /// <seealso cref="Frame.WaitForExpressionAsync(string, WaitForFunctionOptions)"/>852 public Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options = null)853 => MainFrame.WaitForExpressionAsync(script, options ?? new WaitForFunctionOptions());854 /// <summary>855 /// Waits for a selector to be added to the DOM856 /// </summary>857 /// <param name="selector">A selector of an element to wait for</param>858 /// <param name="options">Optional waiting parameters</param>859 /// <returns>A task that resolves when element specified by selector string is added to DOM.860 /// Resolves to `null` if waiting for `hidden: true` and selector is not found in DOM.</returns>861 /// <seealso cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>862 /// <seealso cref="Frame.WaitForSelectorAsync(string, WaitForSelectorOptions)"/>863 public Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)864 => MainFrame.WaitForSelectorAsync(selector, options ?? new WaitForSelectorOptions());865 /// <summary>866 /// Waits for a xpath selector to be added to the DOM867 /// </summary>868 /// <param name="xpath">A xpath selector of an element to wait for</param>869 /// <param name="options">Optional waiting parameters</param>870 /// <returns>A task which resolves when element specified by xpath string is added to DOM. 871 /// Resolves to `null` if waiting for `hidden: true` and xpath is not found in DOM.</returns>872 /// <example>873 /// <code>874 /// <![CDATA[875 /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());876 /// var page = await browser.NewPageAsync();877 /// string currentURL = null;878 /// page879 /// .WaitForXPathAsync("//img")880 /// .ContinueWith(_ => Console.WriteLine("First URL with image: " + currentURL));881 /// foreach (var current in new[] { "https://example.com", "https://google.com", "https://bbc.com" })882 /// {883 /// currentURL = current;884 /// await page.GoToAsync(currentURL);885 /// }886 /// await browser.CloseAsync();887 /// ]]>888 /// </code>889 /// </example>890 /// <seealso cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>891 /// <seealso cref="Frame.WaitForXPathAsync(string, WaitForSelectorOptions)"/>892 public Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)893 => MainFrame.WaitForXPathAsync(xpath, options ?? new WaitForSelectorOptions());894 /// <summary>895 /// This resolves when the page navigates to a new URL or reloads.896 /// It is useful for when you run code which will indirectly cause the page to navigate.897 /// </summary>898 /// <param name="options">navigation options</param>899 /// <returns>Task which resolves to the main resource response. 900 /// In case of multiple redirects, the navigation will resolve with the response of the last redirect.901 /// In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.902 /// </returns>903 /// <remarks>904 /// Usage of the <c>History API</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/History_API"/> to change the URL is considered a navigation905 /// </remarks>906 /// <example>907 /// <code>908 /// <![CDATA[909 /// var navigationTask = page.WaitForNavigationAsync();910 /// await page.ClickAsync("a.my-link");911 /// await navigationTask;912 /// ]]>913 /// </code>914 /// </example>915 public Task<Response> WaitForNavigationAsync(NavigationOptions options = null) => FrameManager.WaitForFrameNavigationAsync(FrameManager.MainFrame, options);916 /// <summary>917 /// Waits for a request.918 /// </summary>919 /// <example>920 /// <code>921 /// <![CDATA[922 /// var firstRequest = await page.WaitForRequestAsync("http://example.com/resource");923 /// return firstRequest.Url;924 /// ]]>925 /// </code>926 /// </example>927 /// <returns>A task which resolves when a matching request was made.</returns>928 /// <param name="url">URL to wait for.</param>929 /// <param name="options">Options.</param>930 public Task<Request> WaitForRequestAsync(string url, WaitForOptions options = null)931 => WaitForRequestAsync(request => request.Url == url, options);932 /// <summary>933 /// Waits for a request.934 /// </summary>935 /// <example>936 /// <code>937 /// <![CDATA[938 /// var request = await page.WaitForRequestAsync(request => request.Url === "http://example.com" && request.Method === HttpMethod.Get;939 /// return request.Url;940 /// ]]>941 /// </code>942 /// </example>943 /// <returns>A task which resolves when a matching request was made.</returns>944 /// <param name="predicate">Function which looks for a matching request.</param>945 /// <param name="options">Options.</param>946 public async Task<Request> WaitForRequestAsync(Func<Request, bool> predicate, WaitForOptions options = null)947 {948 var timeout = options?.Timeout ?? DefaultTimeout;949 var requestTcs = new TaskCompletionSource<Request>(TaskCreationOptions.RunContinuationsAsynchronously);950 void requestEventListener(object sender, RequestEventArgs e)951 {952 if (predicate(e.Request))953 {954 requestTcs.TrySetResult(e.Request);955 FrameManager.NetworkManager.Request -= requestEventListener;956 }957 }958 FrameManager.NetworkManager.Request += requestEventListener;959 await Task.WhenAny(requestTcs.Task, SessionClosedTask).WithTimeout(timeout, t =>960 {961 FrameManager.NetworkManager.Request -= requestEventListener;962 return new TimeoutException($"Timeout of {t.TotalMilliseconds} ms exceeded");963 }).ConfigureAwait(false);964 if (SessionClosedTask.IsFaulted)965 {966 await SessionClosedTask.ConfigureAwait(false);967 }968 return await requestTcs.Task.ConfigureAwait(false);969 }970 /// <summary>971 /// Waits for a response.972 /// </summary>973 /// <example>974 /// <code>975 /// <![CDATA[976 /// var firstResponse = await page.WaitForResponseAsync("http://example.com/resource");977 /// return firstResponse.Url;978 /// ]]>979 /// </code>980 /// </example>981 /// <returns>A task which resolves when a matching response is received.</returns>982 /// <param name="url">URL to wait for.</param>983 /// <param name="options">Options.</param>984 public Task<Response> WaitForResponseAsync(string url, WaitForOptions options = null)985 => WaitForResponseAsync(response => response.Url == url, options);986 /// <summary>987 /// Waits for a response.988 /// </summary>989 /// <example>990 /// <code>991 /// <![CDATA[992 /// var response = await page.WaitForResponseAsync(response => response.Url === "http://example.com" && response.Status === HttpStatus.Ok;993 /// return response.Url;994 /// ]]>995 /// </code>996 /// </example>997 /// <returns>A task which resolves when a matching response is received.</returns>998 /// <param name="predicate">Function which looks for a matching response.</param>999 /// <param name="options">Options.</param>1000 public async Task<Response> WaitForResponseAsync(Func<Response, bool> predicate, WaitForOptions options = null)1001 {1002 var timeout = options?.Timeout ?? DefaultTimeout;1003 var responseTcs = new TaskCompletionSource<Response>(TaskCreationOptions.RunContinuationsAsynchronously);1004 void responseEventListener(object sender, ResponseCreatedEventArgs e)1005 {1006 if (predicate(e.Response))1007 {1008 responseTcs.TrySetResult(e.Response);1009 FrameManager.NetworkManager.Response -= responseEventListener;1010 }1011 }1012 FrameManager.NetworkManager.Response += responseEventListener;1013 await Task.WhenAny(responseTcs.Task, SessionClosedTask).WithTimeout(timeout).ConfigureAwait(false);1014 if (SessionClosedTask.IsFaulted)1015 {1016 await SessionClosedTask.ConfigureAwait(false);1017 }1018 return await responseTcs.Task.ConfigureAwait(false);1019 }1020 /// <summary>1021 /// Navigate to the previous page in history.1022 /// </summary>1023 /// <returns>Task that resolves to the main resource response. In case of multiple redirects, 1024 /// the navigation will resolve with the response of the last redirect. If can not go back, resolves to null.</returns>1025 /// <param name="options">Navigation parameters.</param>1026 public Task<Response> GoBackAsync(NavigationOptions options = null) => GoAsync(-1, options);1027 /// <summary>1028 /// Navigate to the next page in history.1029 /// </summary>1030 /// <returns>Task that resolves to the main resource response. In case of multiple redirects, 1031 /// the navigation will resolve with the response of the last redirect. If can not go forward, resolves to null.</returns>1032 /// <param name="options">Navigation parameters.</param>1033 public Task<Response> GoForwardAsync(NavigationOptions options = null) => GoAsync(1, options);1034 /// <summary>1035 /// Resets the background color and Viewport after taking Screenshots using BurstMode.1036 /// </summary>1037 /// <returns>The burst mode off.</returns>1038 public Task SetBurstModeOffAsync()1039 {1040 return Task.CompletedTask;1041 }1042 #endregion1043 internal void OnPopup(Page popupPage) => Popup?.Invoke(this, new PopupEventArgs { PopupPage = popupPage });1044 #region Private Method1045 internal static async Task<Page> CreateAsync(1046 CDPSession client,1047 Target target,1048 bool ignoreHTTPSErrors,1049 ViewPortOptions defaultViewPort,1050 TaskQueue screenshotTaskQueue)1051 {1052 var page = new Page(client, target, screenshotTaskQueue);1053 await page.InitializeAsync(ignoreHTTPSErrors).ConfigureAwait(false);1054 if (defaultViewPort != null)1055 {1056 await page.SetViewportAsync(defaultViewPort).ConfigureAwait(false);1057 }1058 return page;1059 }1060 private async Task InitializeAsync(bool ignoreHTTPSErrors)1061 {1062 FrameManager = await FrameManager.CreateFrameManagerAsync(Client, this, ignoreHTTPSErrors, _timeoutSettings).ConfigureAwait(false);1063 var networkManager = FrameManager.NetworkManager;1064 Client.MessageReceived += Client_MessageReceived;1065 FrameManager.FrameAttached += (sender, e) => FrameAttached?.Invoke(this, e);1066 FrameManager.FrameDetached += (sender, e) => FrameDetached?.Invoke(this, e);1067 FrameManager.FrameNavigated += (sender, e) => FrameNavigated?.Invoke(this, e);1068 networkManager.Request += (sender, e) => Request?.Invoke(this, e);1069 networkManager.RequestFailed += (sender, e) => RequestFailed?.Invoke(this, e);1070 networkManager.Response += (sender, e) => Response?.Invoke(this, e);1071 networkManager.RequestFinished += (sender, e) => RequestFinished?.Invoke(this, e);1072 await Task.WhenAll(1073 Client.SendAsync("Target.setAutoAttach", new TargetSetAutoAttachRequest1074 {1075 AutoAttach = true,1076 WaitForDebuggerOnStart = false,1077 Flatten = true1078 }),1079 Client.SendAsync("Performance.enable", null),1080 Client.SendAsync("Log.enable", null)1081 ).ConfigureAwait(false);...

Full Screen

Full Screen

Frame.cs

Source:Frame.cs Github

copy

Full Screen

...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>76 public string Url { get; private set; }77 /// <summary>78 /// Gets a value indicating if the frame is detached or not79 /// </summary>80 public bool Detached { get; set; }81 /// <summary>82 /// Gets the parent frame, if any. Detached frames and main frames return <c>null</c>83 /// </summary>84 public Frame ParentFrame { get; private set; }85 internal FrameManager FrameManager { get; }86 #endregion87 #region Public Methods88 /// <summary>89 /// Navigates to an url90 /// </summary>91 /// <remarks>92 /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will throw an error if:93 /// - there's an SSL error (e.g. in case of self-signed certificates).94 /// - target URL is invalid.95 /// - the `timeout` is exceeded during navigation.96 /// - the remote server does not respond or is unreachable.97 /// - the main resource failed to load.98 /// 99 /// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will not throw an error when any valid HTTP status code is returned by the remote server, 100 /// including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling <see cref="Response.Status"/>101 /// 102 /// > **NOTE** <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> either throws an error or returns a main resource response. 103 /// The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.104 /// 105 /// > **NOTE** Headless mode doesn't support navigation to a PDF document. See the <see fref="https://bugs.chromium.org/p/chromium/issues/detail?id=761295">upstream issue</see>.106 /// </remarks>107 /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>108 /// <param name="options">Navigation parameters.</param>109 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.</returns>110 /// <seealso cref="GoToAsync(string, int?, WaitUntilNavigation[])"/>111 public Task<Response> GoToAsync(string url, NavigationOptions options) => FrameManager.NavigateFrameAsync(this, url, options);112 /// <summary>113 /// Navigates to an url114 /// </summary>115 /// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>116 /// <param name="timeout">maximum navigation time in milliseconds. Defaults to 30 seconds. Pass 0117 /// to disable timeout. The default value can be changed by using the <see cref="Page.DefaultNavigationTimeout"/>118 /// property.</param>119 /// <param name="waitUntil">When to consider navigation succeeded, defaults to <see cref="WaitUntilNavigation.Load"/>. Given an array of <see cref="WaitUntilNavigation"/>, navigation is considered to be successful after all events have been fired</param>120 /// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>121 public Task<Response> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)122 => GoToAsync(url, new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });123 /// <summary>124 /// This resolves when the frame navigates to a new URL or reloads.125 /// It is useful for when you run code which will indirectly cause the frame to navigate.126 /// </summary>127 /// <param name="options">navigation options</param>128 /// <returns>Task which resolves to the main resource response. 129 /// In case of multiple redirects, the navigation will resolve with the response of the last redirect.130 /// In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.131 /// </returns>132 /// <remarks>133 /// Usage of the <c>History API</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/History_API"/> to change the URL is considered a navigation134 /// </remarks>135 /// <example>136 /// <code>137 /// <![CDATA[138 /// var navigationTask =frame.page.WaitForNavigationAsync();139 /// await frame.ClickAsync("a.my-link");140 /// await navigationTask;141 /// ]]>142 /// </code>143 /// </example>144 public Task<Response> WaitForNavigationAsync(NavigationOptions options = null) => FrameManager.WaitForFrameNavigationAsync(this, options);145 /// <summary>146 /// Executes a script in browser context147 /// </summary>148 /// <param name="script">Script to be evaluated in browser context</param>149 /// <remarks>150 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.151 /// </remarks>152 /// <returns>Task which resolves to script return value</returns>153 /// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>154 /// <seealso cref="Page.EvaluateExpressionAsync{T}(string)"/>155 public Task<JToken> EvaluateExpressionAsync(string script) => MainWorld.EvaluateExpressionAsync(script);156 /// <summary>157 /// Executes a script in browser context158 /// </summary>...

Full Screen

Full Screen

FrameManager.cs

Source:FrameManager.cs Github

copy

Full Screen

...9using PuppeteerSharp.Helpers.Json;10using PuppeteerSharp.Messaging;11namespace PuppeteerSharp12{13 internal class FrameManager14 {15 private Dictionary<int, ExecutionContext> _contextIdToContext;16 private bool _ensureNewDocumentNavigation;17 private readonly ILogger _logger;18 private readonly ConcurrentDictionary<string, Frame> _frames;19 private const string RefererHeaderName = "referer";20 private readonly AsyncDictionaryHelper<string, Frame> _asyncFrames;21 private readonly List<string> _isolatedWorlds = new List<string>();22 private const string UtilityWorldName = "__puppeteer_utility_world__";23 private FrameManager(CDPSession client, Page page, bool ignoreHTTPSErrors, TimeoutSettings timeoutSettings)24 {25 Client = client;26 Page = page;27 _frames = new ConcurrentDictionary<string, Frame>();28 _contextIdToContext = new Dictionary<int, ExecutionContext>();29 _logger = Client.Connection.LoggerFactory.CreateLogger<FrameManager>();30 NetworkManager = new NetworkManager(client, ignoreHTTPSErrors);31 NetworkManager.FrameManager = this;32 TimeoutSettings = timeoutSettings;33 _asyncFrames = new AsyncDictionaryHelper<string, Frame>(_frames, "Frame {0} not found");34 Client.MessageReceived += Client_MessageReceived;35 }36 #region Properties37 internal event EventHandler<FrameEventArgs> FrameAttached;38 internal event EventHandler<FrameEventArgs> FrameDetached;39 internal event EventHandler<FrameEventArgs> FrameNavigated;40 internal event EventHandler<FrameEventArgs> FrameNavigatedWithinDocument;41 internal event EventHandler<FrameEventArgs> LifecycleEvent;42 internal CDPSession Client { get; }43 internal NetworkManager NetworkManager { get; }44 internal Frame MainFrame { get; set; }45 internal Page Page { get; }46 internal TimeoutSettings TimeoutSettings { get; }47 #endregion48 #region Public Methods49 internal static async Task<FrameManager> CreateFrameManagerAsync(50 CDPSession client,51 Page page,52 bool ignoreHTTPSErrors,53 TimeoutSettings timeoutSettings)54 {55 var frameManager = new FrameManager(client, page, ignoreHTTPSErrors, timeoutSettings);56 var getFrameTreeTask = client.SendAsync<PageGetFrameTreeResponse>("Page.getFrameTree");57 await Task.WhenAll(58 client.SendAsync("Page.enable"),59 getFrameTreeTask).ConfigureAwait(false);60 await frameManager.HandleFrameTreeAsync(new FrameTree(getFrameTreeTask.Result.FrameTree)).ConfigureAwait(false);61 await Task.WhenAll(62 client.SendAsync("Page.setLifecycleEventsEnabled", new PageSetLifecycleEventsEnabledRequest { Enabled = true }),63 client.SendAsync("Runtime.enable"),64 frameManager.NetworkManager.InitializeAsync()).ConfigureAwait(false);65 await frameManager.EnsureIsolatedWorldAsync().ConfigureAwait(false);66 return frameManager;67 }68 internal ExecutionContext ExecutionContextById(int contextId)69 {...

Full Screen

Full Screen

NetworkManager.cs

Source:NetworkManager.cs Github

copy

Full Screen

...25 private bool _protocolRequestInterceptionEnabled;26 private bool _ignoreHTTPSErrors;27 private bool _userCacheDisabled;28 #endregion29 internal NetworkManager(CDPSession client, bool ignoreHTTPSErrors, FrameManager frameManager)30 {31 FrameManager = frameManager;32 _client = client;33 _ignoreHTTPSErrors = ignoreHTTPSErrors;34 _client.MessageReceived += Client_MessageReceived;35 _logger = _client.Connection.LoggerFactory.CreateLogger<NetworkManager>();36 }37 #region Public Properties38 internal Dictionary<string, string> ExtraHTTPHeaders => _extraHTTPHeaders?.Clone();39 internal event EventHandler<ResponseCreatedEventArgs> Response;40 internal event EventHandler<RequestEventArgs> Request;41 internal event EventHandler<RequestEventArgs> RequestFinished;42 internal event EventHandler<RequestEventArgs> RequestFailed;43 internal FrameManager FrameManager { get; set; }44 #endregion45 #region Public Methods46 internal async Task InitializeAsync()47 {48 await _client.SendAsync("Network.enable").ConfigureAwait(false);49 if (_ignoreHTTPSErrors)50 {51 await _client.SendAsync("Security.setIgnoreCertificateErrors", new SecuritySetIgnoreCertificateErrorsRequest52 {53 Ignore = true54 }).ConfigureAwait(false);55 }56 }57 internal Task AuthenticateAsync(Credentials credentials)58 {59 _credentials = credentials;60 return UpdateProtocolRequestInterceptionAsync();61 }62 internal Task SetExtraHTTPHeadersAsync(Dictionary<string, string> extraHTTPHeaders)63 {64 _extraHTTPHeaders = new Dictionary<string, string>();65 foreach (var item in extraHTTPHeaders)66 {67 _extraHTTPHeaders[item.Key.ToLower()] = item.Value;68 }69 return _client.SendAsync("Network.setExtraHTTPHeaders", new NetworkSetExtraHTTPHeadersRequest70 {71 Headers = _extraHTTPHeaders72 });73 }74 internal async Task SetOfflineModeAsync(bool value)75 {76 if (_offine != value)77 {78 _offine = value;79 await _client.SendAsync("Network.emulateNetworkConditions", new NetworkEmulateNetworkConditionsRequest80 {81 Offline = value,82 Latency = 0,83 DownloadThroughput = -1,84 UploadThroughput = -185 }).ConfigureAwait(false);86 }87 }88 internal Task SetUserAgentAsync(string userAgent)89 => _client.SendAsync("Network.setUserAgentOverride", new NetworkSetUserAgentOverrideRequest90 {91 UserAgent = userAgent92 });93 internal Task SetCacheEnabledAsync(bool enabled)94 {95 _userCacheDisabled = !enabled;96 return UpdateProtocolCacheDisabledAsync();97 }98 internal Task SetRequestInterceptionAsync(bool value)99 {100 _userRequestInterceptionEnabled = value;101 return UpdateProtocolRequestInterceptionAsync();102 }103 #endregion104 #region Private Methods105 private Task UpdateProtocolCacheDisabledAsync()106 => _client.SendAsync("Network.setCacheDisabled", new NetworkSetCacheDisabledRequest107 {108 CacheDisabled = _userCacheDisabled || _protocolRequestInterceptionEnabled109 });110 private async void Client_MessageReceived(object sender, MessageEventArgs e)111 {112 try113 {114 switch (e.MessageID)115 {116 case "Fetch.requestPaused":117 await OnRequestPausedAsync(e.MessageData.ToObject<FetchRequestPausedResponse>(true));118 break;119 case "Fetch.authRequired":120 await OnAuthRequiredAsync(e.MessageData.ToObject<FetchAuthRequiredResponse>(true));121 break;122 case "Network.requestWillBeSent":123 await OnRequestWillBeSentAsync(e.MessageData.ToObject<RequestWillBeSentPayload>(true));124 break;125 case "Network.requestServedFromCache":126 OnRequestServedFromCache(e.MessageData.ToObject<RequestServedFromCacheResponse>(true));127 break;128 case "Network.responseReceived":129 OnResponseReceived(e.MessageData.ToObject<ResponseReceivedResponse>(true));130 break;131 case "Network.loadingFinished":132 OnLoadingFinished(e.MessageData.ToObject<LoadingFinishedResponse>(true));133 break;134 case "Network.loadingFailed":135 OnLoadingFailed(e.MessageData.ToObject<LoadingFailedResponse>(true));136 break;137 }138 }139 catch (Exception ex)140 {141 var message = $"NetworkManager failed to process {e.MessageID}. {ex.Message}. {ex.StackTrace}";142 _logger.LogError(ex, message);143 _client.Close(message);144 }145 }146 private void OnLoadingFailed(LoadingFailedResponse e)147 {148 // For certain requestIds we never receive requestWillBeSent event.149 // @see https://crbug.com/750469150 if (_requestIdToRequest.TryGetValue(e.RequestId, out var request))151 {152 request.Failure = e.ErrorText;153 request.Response?.BodyLoadedTaskWrapper.TrySetResult(true);154 _requestIdToRequest.TryRemove(request.RequestId, out _);155 if (request.InterceptionId != null)156 {157 _attemptedAuthentications.Remove(request.InterceptionId);158 }159 RequestFailed?.Invoke(this, new RequestEventArgs160 {161 Request = request162 });163 }164 }165 private void OnLoadingFinished(LoadingFinishedResponse e)166 {167 // For certain requestIds we never receive requestWillBeSent event.168 // @see https://crbug.com/750469169 if (_requestIdToRequest.TryGetValue(e.RequestId, out var request))170 {171 request.Response?.BodyLoadedTaskWrapper.TrySetResult(true);172 _requestIdToRequest.TryRemove(request.RequestId, out _);173 if (request.InterceptionId != null)174 {175 _attemptedAuthentications.Remove(request.InterceptionId);176 }177 RequestFinished?.Invoke(this, new RequestEventArgs178 {179 Request = request180 });181 }182 }183 private void OnResponseReceived(ResponseReceivedResponse e)184 {185 // FileUpload sends a response without a matching request.186 if (_requestIdToRequest.TryGetValue(e.RequestId, out var request))187 {188 var response = new Response(189 _client,190 request,191 e.Response);192 request.Response = response;193 Response?.Invoke(this, new ResponseCreatedEventArgs194 {195 Response = response196 });197 }198 }199 private async Task OnAuthRequiredAsync(FetchAuthRequiredResponse e)200 {201 var response = "Default";202 if (_attemptedAuthentications.Contains(e.RequestId))203 {204 response = "CancelAuth";205 }206 else if (_credentials != null)207 {208 response = "ProvideCredentials";209 _attemptedAuthentications.Add(e.RequestId);210 }211 var credentials = _credentials ?? new Credentials();212 try213 {214 await _client.SendAsync("Fetch.continueWithAuth", new ContinueWithAuthRequest215 {216 RequestId = e.RequestId,217 AuthChallengeResponse = new ContinueWithAuthRequestChallengeResponse218 {219 Response = response,220 Username = credentials.Username,221 Password = credentials.Password222 }223 }).ConfigureAwait(false);224 }225 catch (PuppeteerException ex)226 {227 _logger.LogError(ex.ToString());228 }229 }230 private async Task OnRequestPausedAsync(FetchRequestPausedResponse e)231 {232 if (!_userRequestInterceptionEnabled && _protocolRequestInterceptionEnabled)233 {234 try235 {236 await _client.SendAsync("Fetch.continueRequest", new FetchContinueRequestRequest237 {238 RequestId = e.RequestId239 }).ConfigureAwait(false);240 }241 catch (PuppeteerException ex)242 {243 _logger.LogError(ex.ToString());244 }245 }246 var requestId = e.NetworkId;247 var interceptionId = e.RequestId;248 if (!string.IsNullOrEmpty(requestId))249 {250 if (_requestIdToRequestWillBeSentEvent.TryRemove(requestId, out var requestWillBeSentEvent))251 {252 await OnRequestAsync(requestWillBeSentEvent, interceptionId).ConfigureAwait(false);253 }254 else255 {256 _requestIdToInterceptionId[requestId] = interceptionId;257 }258 }259 }260 private async Task OnRequestAsync(RequestWillBeSentPayload e, string interceptionId)261 {262 Request request;263 var redirectChain = new List<Request>();264 if (e.RedirectResponse != null)265 {266 _requestIdToRequest.TryGetValue(e.RequestId, out request);267 // If we connect late to the target, we could have missed the requestWillBeSent event.268 if (request != null)269 {270 HandleRequestRedirect(request, e.RedirectResponse);271 redirectChain = request.RedirectChainList;272 }273 }274 if (!_requestIdToRequest.TryGetValue(e.RequestId, out var currentRequest) ||275 currentRequest.Frame == null)276 {277 var frame = await FrameManager.GetFrameAsync(e.FrameId);278 request = new Request(279 _client,280 frame,281 interceptionId,282 _userRequestInterceptionEnabled,283 e,284 redirectChain);285 _requestIdToRequest[e.RequestId] = request;286 Request?.Invoke(this, new RequestEventArgs287 {288 Request = request289 });290 }291 }...

Full Screen

Full Screen

DOMWorld.cs

Source:DOMWorld.cs Github

copy

Full Screen

...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

LifecycleWatcher.cs

Source:LifecycleWatcher.cs Github

copy

Full Screen

...16 [WaitUntilNavigation.Networkidle0] = "networkIdle",17 [WaitUntilNavigation.Networkidle2] = "networkAlmostIdle"18 };19 private static readonly WaitUntilNavigation[] _defaultWaitUntil = { WaitUntilNavigation.Load };20 private readonly FrameManager _frameManager;21 private readonly Frame _frame;22 private readonly IEnumerable<string> _expectedLifecycle;23 private readonly int _timeout;24 private readonly string _initialLoaderId;25 private Request _navigationRequest;26 private bool _hasSameDocumentNavigation;27 private TaskCompletionSource<bool> _newDocumentNavigationTaskWrapper;28 private TaskCompletionSource<bool> _sameDocumentNavigationTaskWrapper;29 private TaskCompletionSource<bool> _lifecycleTaskWrapper;30 private TaskCompletionSource<bool> _terminationTaskWrapper;31 public LifecycleWatcher(32 FrameManager frameManager,33 Frame frame,34 WaitUntilNavigation[] waitUntil,35 int timeout)36 {37 _expectedLifecycle = (waitUntil ?? _defaultWaitUntil).Select(w =>38 {39 var protocolEvent = _puppeteerToProtocolLifecycle.GetValueOrDefault(w);40 Contract.Assert(protocolEvent != null, $"Unknown value for options.waitUntil: {w}");41 return protocolEvent;42 });43 _frameManager = frameManager;44 _frame = frame;45 _initialLoaderId = frame.LoaderId;46 _timeout = timeout;47 _hasSameDocumentNavigation = false;48 _sameDocumentNavigationTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);49 _newDocumentNavigationTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);50 _lifecycleTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);51 _terminationTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);52 frameManager.LifecycleEvent += FrameManager_LifecycleEvent;53 frameManager.FrameNavigatedWithinDocument += NavigatedWithinDocument;54 frameManager.FrameDetached += OnFrameDetached;55 frameManager.NetworkManager.Request += OnRequest;56 frameManager.Client.Disconnected += OnClientDisconnected;57 CheckLifecycleComplete();58 }59 #region Properties60 public Task<Task> NavigationTask { get; internal set; }61 public Task<bool> SameDocumentNavigationTask => _sameDocumentNavigationTaskWrapper.Task;62 public Task<bool> NewDocumentNavigationTask => _newDocumentNavigationTaskWrapper.Task;63 public Response NavigationResponse => _navigationRequest?.Response;64 public Task TimeoutOrTerminationTask65 => _terminationTaskWrapper.Task.WithTimeout(_timeout);66 public Task LifecycleTask => _lifecycleTaskWrapper.Task;67 #endregion68 #region Private methods69 private void OnClientDisconnected(object sender, EventArgs e)70 => Terminate(new TargetClosedException("Navigation failed because browser has disconnected!", _frameManager.Client.CloseReason));71 void FrameManager_LifecycleEvent(object sender, FrameEventArgs e) => CheckLifecycleComplete();7273 private void OnFrameDetached(object sender, FrameEventArgs e)74 {75 var frame = e.Frame;76 if (_frame == frame)77 {78 Terminate(new PuppeteerException("Navigating frame was detached"));79 return;80 }81 CheckLifecycleComplete();82 }83 private void CheckLifecycleComplete()84 {85 // We expect navigation to commit.86 if (!CheckLifecycle(_frame, _expectedLifecycle))87 {88 return;89 }90 _lifecycleTaskWrapper.TrySetResult(true);91 if (_frame.LoaderId == _initialLoaderId && !_hasSameDocumentNavigation)92 {93 return;94 }95 if (_hasSameDocumentNavigation)96 {97 _sameDocumentNavigationTaskWrapper.TrySetResult(true);98 }99 if (_frame.LoaderId != _initialLoaderId)100 {101 _newDocumentNavigationTaskWrapper.TrySetResult(true);102 }103 }104 private void Terminate(PuppeteerException ex) => _terminationTaskWrapper.TrySetException(ex);105 private void OnRequest(object sender, RequestEventArgs e)106 {107 if (e.Request.Frame != _frame || !e.Request.IsNavigationRequest)108 {109 return;110 }111 _navigationRequest = e.Request;112 }113 private void NavigatedWithinDocument(object sender, FrameEventArgs e)114 {115 if (e.Frame != _frame)116 {117 return;118 }119 _hasSameDocumentNavigation = true;120 CheckLifecycleComplete();121 }122 private bool CheckLifecycle(Frame frame, IEnumerable<string> expectedLifecycle)123 {124 foreach (var item in expectedLifecycle)125 {126 if (!frame.LifecycleEvents.Contains(item))127 {128 return false;129 }130 }131 foreach (var child in frame.ChildFrames)132 {133 if (!CheckLifecycle(child, expectedLifecycle))134 {135 return false;136 }137 }138 return true;139 }140 public void Dispose() => Dispose(true);141 ~LifecycleWatcher() => Dispose(false);142 public void Dispose(bool disposing)143 {144 _frameManager.LifecycleEvent -= FrameManager_LifecycleEvent;145 _frameManager.FrameNavigatedWithinDocument -= NavigatedWithinDocument;146 _frameManager.FrameDetached -= OnFrameDetached;147 _frameManager.NetworkManager.Request -= OnRequest;148 _frameManager.Client.Disconnected -= OnClientDisconnected;149 }150 #endregion151 }152}...

Full Screen

Full Screen

NavigatorWatcher.cs

Source:NavigatorWatcher.cs Github

copy

Full Screen

...16 [WaitUntilNavigation.DOMContentLoaded] = "DOMContentLoaded",17 [WaitUntilNavigation.Networkidle0] = "networkIdle",18 [WaitUntilNavigation.Networkidle2] = "networkAlmostIdle"19 };20 private FrameManager _frameManager;21 private Frame _frame;22 private NavigationOptions _options;23 private IEnumerable<string> _expectedLifecycle;24 private int _timeout;25 private string _initialLoaderId;26 public NavigatorWatcher(FrameManager frameManager, Frame mainFrame, int timeout, NavigationOptions options)27 {28 var waitUntil = new[] { WaitUntilNavigation.Load };2930 if (options?.WaitUntil != null)31 {32 waitUntil = options.WaitUntil;33 }3435 _expectedLifecycle = waitUntil.Select(w =>36 {37 var protocolEvent = _puppeteerToProtocolLifecycle.GetValueOrDefault(w);38 Contract.Assert(protocolEvent != null, $"Unknown value for options.waitUntil: {w}");39 return protocolEvent;40 });4142 _frameManager = frameManager;43 _frame = mainFrame;44 _options = options;45 _initialLoaderId = mainFrame.LoaderId;46 _timeout = timeout;4748 frameManager.LifecycleEvent += FrameManager_LifecycleEvent;49 frameManager.FrameDetached += FrameManager_LifecycleEvent;50 LifeCycleCompleteTaskWrapper = new TaskCompletionSource<bool>();5152 NavigationTask = Task.WhenAny(new[]53 {54 CreateTimeoutTask(),55 LifeCycleCompleteTask,56 }).ContinueWith((task) =>57 {58 CleanUp();59 return task.GetAwaiter().GetResult();60 });61 }62 #region Properties63 public Task<Task> NavigationTask { get; internal set; }64 public Task<bool> LifeCycleCompleteTask => LifeCycleCompleteTaskWrapper.Task;65 public TaskCompletionSource<bool> LifeCycleCompleteTaskWrapper { get; }66 #endregion67 #region Public methods68 public void Cancel()69 {70 CleanUp();71 }72 #endregion73 #region Private methods74 void FrameManager_LifecycleEvent(object sender, FrameEventArgs e)75 {76 // We expect navigation to commit.77 if (_frame.LoaderId == _initialLoaderId)78 {79 return;80 }81 if (!CheckLifecycle(_frame, _expectedLifecycle))82 {83 return;84 }8586 if (!LifeCycleCompleteTaskWrapper.Task.IsCompleted)87 {88 LifeCycleCompleteTaskWrapper.SetResult(true);89 }90 }9192 private bool CheckLifecycle(Frame frame, IEnumerable<string> expectedLifecycle)93 {94 foreach (var item in expectedLifecycle)95 {96 if (!frame.LifecycleEvents.Contains(item))97 {98 return false;99 }100 }101 foreach (var child in frame.ChildFrames)102 {103 if (!CheckLifecycle(child, expectedLifecycle))104 {105 return false;106 }107 }108 return true;109 }110 private void CleanUp()111 {112 _frameManager.LifecycleEvent -= FrameManager_LifecycleEvent;113 _frameManager.FrameDetached -= FrameManager_LifecycleEvent;114 }115 private async Task CreateTimeoutTask()116 {117 var wrapper = new TaskCompletionSource<bool>();118119 if (_timeout == 0)120 {121 await Task.Delay(-1);122 }123 else124 {125 await Task.Delay(_timeout);126 throw new NavigationException($"Navigation Timeout Exceeded: {_timeout}ms exceeded");127 } ...

Full Screen

Full Screen

FrameManager

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.ScreenshotAsync("google.png");12 await browser.CloseAsync();13 }14 }15}16using System;17using System.Threading.Tasks;18using PuppeteerSharp;19{20 {21 static async Task Main(string[] args)22 {23 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);24 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });25 var page = await browser.NewPageAsync();26 await page.ScreenshotAsync("google.png");27 await browser.CloseAsync();28 }29 }30}31using System;32using System.Threading.Tasks;33using PuppeteerSharp;34{35 {36 static async Task Main(string[] args)37 {38 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);39 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });40 var page = await browser.NewPageAsync();41 await page.ScreenshotAsync("google.png");42 await browser.CloseAsync();43 }44 }45}46using System;47using System.Threading.Tasks;48using PuppeteerSharp;49{50 {51 static async Task Main(string[] args)52 {53 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);54 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });55 var page = await browser.NewPageAsync();

Full Screen

Full Screen

FrameManager

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 = false };9 using (var browser = await Puppeteer.LaunchAsync(options))10 using (var page = await browser.NewPageAsync())11 {12 await page.ScreenshotAsync("google.png");13 var frameManager = page.FrameManager;14 var frame = frameManager.MainFrame;15 var frameUrl = frame.Url;16 Console.WriteLine(frameUrl);17 }18 }19 }20}

Full Screen

Full Screen

FrameManager

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 options = new LaunchOptions { Headless = false };13 using (var browser = await Puppeteer.LaunchAsync(options))14 using (var page = await browser.NewPageAsync())15 {16 await page.ScreenshotAsync("google.png");17 FrameManager frameManager = page.FrameManager;18 Console.WriteLine("FrameManager is: " + frameManager);19 }20 }21 }22}23PuppeteerSharp | Frame class | EvaluateHandleAsync() method24PuppeteerSharp | Frame class | EvaluateExpressionHandleAsync() method25PuppeteerSharp | Frame class | EvaluateExpressionAsync() method26PuppeteerSharp | Frame class | EvaluateFunctionHandleAsync() method27PuppeteerSharp | Frame class | EvaluateFunctionAsync() method28PuppeteerSharp | Frame class | AddScriptTagAsync() method29PuppeteerSharp | Frame class | AddStyleTagAsync() method30PuppeteerSharp | Frame class | ClickAsync() method31PuppeteerSharp | Frame class | ContentAsync() method32PuppeteerSharp | Frame class | DetachAsync() method33PuppeteerSharp | Frame class | EvaluateHandleAsync() method34PuppeteerSharp | Frame class | EvaluateExpressionHandleAsync() method35PuppeteerSharp | Frame class | EvaluateExpressionAsync() method36PuppeteerSharp | Frame class | EvaluateFunctionHandleAsync() method37PuppeteerSharp | Frame class | EvaluateFunctionAsync() method38PuppeteerSharp | Frame class | AddScriptTagAsync() method39PuppeteerSharp | Frame class | AddStyleTagAsync() method40PuppeteerSharp | Frame class | ClickAsync() method41PuppeteerSharp | Frame class | ContentAsync() method42PuppeteerSharp | Frame class | DetachAsync() method

Full Screen

Full Screen

FrameManager

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);10 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))11 using (var page = await browser.NewPageAsync())12 {13 await page.TypeAsync("input[name=q]", "Puppeteer Sharp");14 await page.Keyboard.PressAsync("Enter");15 await page.ScreenshotAsync("puppeteer-sharp.png");16 }17 }18 }19}

Full Screen

Full Screen

FrameManager

Using AI Code Generation

copy

Full Screen

1var frameManager = await page.GetFrameManagerAsync();2var frame = await frameManager.GetFrameAsync("frameId");3var frame = await page.GetFrameAsync("frameId");4var frameManager = await frame.GetFrameManagerAsync();5var frameManager = await page.GetFrameManagerAsync();6var frame = await frameManager.GetFrameAsync("frameId");7var frameManager = await page.GetFrameManagerAsync();8var frame = await frameManager.GetFrameAsync("frameId");9var frame = await page.GetFrameAsync("frameId");10var frameManager = await frame.GetFrameManagerAsync();11var frame = await page.GetFrameAsync("frameId");12var frameManager = await frame.GetFrameManagerAsync();13var frame = await page.GetFrameAsync("frameId");14var frameManager = await frame.GetFrameManagerAsync();15var frameManager = await page.GetFrameManagerAsync();16var frame = await frameManager.GetFrameAsync("frameId");17var frameManager = await page.GetFrameManagerAsync();18var frame = await frameManager.GetFrameAsync("frameId");19var frame = await page.GetFrameAsync("frameId");20var frameManager = await frame.GetFrameManagerAsync();21var frameManager = await page.GetFrameManagerAsync();22var frame = await frameManager.GetFrameAsync("frameId");

Full Screen

Full Screen

FrameManager

Using AI Code Generation

copy

Full Screen

1var frameManager = await page.GetFrameManagerAsync();2var frame = await frameManager.GetFrameAsync("frame1");3await frame.SetContentAsync("Hello World!");4var frameManager = await page.GetFrameManagerAsync();5var frame = await frameManager.GetFrameAsync("frame1");6await frame.SetContentAsync("Hello World!");7var frameManager = await page.GetFrameManagerAsync();8var frame = await frameManager.GetFrameAsync("frame1");9await frame.SetContentAsync("Hello World!");10var frameManager = await page.GetFrameManagerAsync();11var frame = await frameManager.GetFrameAsync("frame1");12await frame.SetContentAsync("Hello World!");13var frameManager = await page.GetFrameManagerAsync();14var frame = await frameManager.GetFrameAsync("frame1");15await frame.SetContentAsync("Hello World!");16var frameManager = await page.GetFrameManagerAsync();17var frame = await frameManager.GetFrameAsync("frame1");18await frame.SetContentAsync("Hello World!");19var frameManager = await page.GetFrameManagerAsync();20var frame = await frameManager.GetFrameAsync("frame1");21await frame.SetContentAsync("Hello World!");22var frameManager = await page.GetFrameManagerAsync();23var frame = await frameManager.GetFrameAsync("frame1");24await frame.SetContentAsync("Hello World!");25var frameManager = await page.GetFrameManagerAsync();26var frame = await frameManager.GetFrameAsync("frame1");27await frame.SetContentAsync("Hello World!");

Full Screen

Full Screen

FrameManager

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().GetAwaiter().GetResult();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 });15 var page = await browser.NewPageAsync();16 var frameManager = page.FrameManager;17 var frame = frameManager.MainFrame;18 var frameUrl = frame.Url;19 Console.WriteLine(frameUrl);20 await browser.CloseAsync();21 }22 }23}24using System;25using System.Threading.Tasks;26using PuppeteerSharp;27{28 {29 static void Main(string[] args)30 {31 MainAsync().GetAwaiter().GetResult();32 }33 static async Task MainAsync()34 {35 var browser = await Puppeteer.LaunchAsync(new LaunchOptions36 {37 });38 var page = await browser.NewPageAsync();39 var frameManager = page.FrameManager;40 var frame = frameManager.MainFrame;41 var frameUrl = frame.Url;42 Console.WriteLine(frameUrl);43 var frameName = frame.Name;44 Console.WriteLine(frameName);

Full Screen

Full Screen

FrameManager

Using AI Code Generation

copy

Full Screen

1using System.Threading.Tasks;2using PuppeteerSharp;3{4 {5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });9 var page = await browser.NewPageAsync();10 var frameManager = page.FrameManager;11 var title = await newPage.TitleAsync();12 var url = await newPage.UrlAsync();13 var content = await newPage.GetContentAsync();14 await browser.CloseAsync();15 }16 }17}18using System.Threading.Tasks;19using PuppeteerSharp;20{21 {22 static async Task Main(string[] args)23 {24 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);25 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });26 var page = await browser.NewPageAsync();27 var frameManager = page.FrameManager;28 var title = await newPage.TitleAsync();29 var url = await newPage.UrlAsync();30 var content = await newPage.GetContentAsync();31 await browser.CloseAsync();32 }33 }34}

Full Screen

Full Screen

FrameManager

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 Console.WriteLine("Hello World!");9 var options = new LaunchOptions { Headless = false };10 using (var browser = await Puppeteer.LaunchAsync(options))11 using (var page = await browser.NewPageAsync())12 {13 var frame = await page.FrameManager.FrameAsync("frame1");14 var element = await frame.QuerySelectorAsync("#frame1");15 var attributeValue = await element.GetAttributeAsync("name");16 var textValue = await element.GetAttributeAsync("innerText");17 var length = textValue.Length;18 Console.WriteLine("Attribute Value: " + attributeValue);19 Console.WriteLine("Text Value: " + textValue);20 Console.WriteLine("Length of the Text Value: " + length);21 }22 }23 }24}

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