How to use OnRoute method of Microsoft.Playwright.Core.BrowserContext class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.BrowserContext.OnRoute

Page.cs

Source:Page.cs Github

copy

Full Screen

...74 _channel.Crashed += Channel_Crashed;75 _channel.Popup += (_, e) => Popup?.Invoke(this, e.Page);76 _channel.WebSocket += (_, e) => WebSocket?.Invoke(this, e);77 _channel.BindingCall += Channel_BindingCall;78 _channel.Route += (_, e) => OnRoute(e.Route, e.Request);79 _channel.FrameAttached += Channel_FrameAttached;80 _channel.FrameDetached += Channel_FrameDetached;81 _channel.Dialog += (_, e) =>82 {83 if (Dialog == null)84 {85 if ("beforeunload".Equals(e.Type, StringComparison.Ordinal))86 {87 e.AcceptAsync(null).IgnoreException();88 }89 else90 {91 e.DismissAsync().IgnoreException();92 }93 }94 else95 {96 Dialog?.Invoke(this, e);97 }98 };99 _channel.Console += (_, e) => Console?.Invoke(this, e);100 _channel.DOMContentLoaded += (_, _) => DOMContentLoaded?.Invoke(this, this);101 _channel.Download += (_, e) => Download?.Invoke(this, new Download(this, e.Url, e.SuggestedFilename, e.Artifact.Object));102 _channel.PageError += (_, e) => PageError?.Invoke(this, e.ToString());103 _channel.Load += (_, _) => Load?.Invoke(this, this);104 _channel.Video += (_, e) => ForceVideo().ArtifactReady(e.Artifact);105 _channel.FileChooser += (_, e) => _fileChooserEventHandler?.Invoke(this, new FileChooser(this, e.Element.Object, e.IsMultiple));106 _channel.Worker += (_, e) =>107 {108 WorkersList.Add(e.WorkerChannel.Object);109 e.WorkerChannel.Object.Page = this;110 Worker?.Invoke(this, e.WorkerChannel.Object);111 };112 _defaultNavigationTimeout = Context.DefaultNavigationTimeout;113 _defaultTimeout = Context.DefaultTimeout;114 _initializer = initializer;115 Close += (_, _) => ClosedOrCrashedTcs.TrySetResult(true);116 Crash += (_, _) => ClosedOrCrashedTcs.TrySetResult(true);117 }118 public event EventHandler<IConsoleMessage> Console;119 public event EventHandler<IPage> Popup;120 public event EventHandler<IRequest> Request;121 public event EventHandler<IWebSocket> WebSocket;122 public event EventHandler<IResponse> Response;123 public event EventHandler<IRequest> RequestFinished;124 public event EventHandler<IRequest> RequestFailed;125 public event EventHandler<IDialog> Dialog;126 public event EventHandler<IFrame> FrameAttached;127 public event EventHandler<IFrame> FrameDetached;128 public event EventHandler<IFrame> FrameNavigated;129 public event EventHandler<IFileChooser> FileChooser130 {131 add132 {133 lock (_fileChooserEventLock)134 {135 _fileChooserEventHandler += value;136 _fileChooserIntercepted = true;137 _channel.SetFileChooserInterceptedNoReplyAsync(true).IgnoreException();138 }139 }140 remove141 {142 lock (_fileChooserEventLock)143 {144 _fileChooserEventHandler -= value;145 if (_fileChooserIntercepted)146 {147 _fileChooserIntercepted = false;148 _channel.SetFileChooserInterceptedNoReplyAsync(false).IgnoreException();149 }150 }151 }152 }153 public event EventHandler<IPage> Load;154 public event EventHandler<IPage> DOMContentLoaded;155 public event EventHandler<IPage> Close;156 public event EventHandler<IPage> Crash;157 public event EventHandler<string> PageError;158 public event EventHandler<IWorker> Worker;159 public event EventHandler<IDownload> Download;160 ChannelBase IChannelOwner.Channel => _channel;161 IChannel<Page> IChannelOwner<Page>.Channel => _channel;162 public bool IsClosed { get; private set; }163 IFrame IPage.MainFrame => MainFrame;164 public Frame MainFrame { get; }165 IBrowserContext IPage.Context => Context;166 public BrowserContext Context { get; set; }167 public PageViewportSizeResult ViewportSize { get; private set; }168 public IAccessibility Accessibility169 {170 get => _accessibility;171 set => throw new NotSupportedException();172 }173 public IMouse Mouse174 {175 get => _mouse;176 set => throw new NotSupportedException();177 }178 public string Url => MainFrame.Url;179 public IReadOnlyList<IFrame> Frames => _frames.AsReadOnly();180 public IKeyboard Keyboard181 {182 get => _keyboard;183 }184 public ITouchscreen Touchscreen185 {186 get => _touchscreen;187 }188 public IReadOnlyList<IWorker> Workers => WorkersList;189 public IVideo Video190 {191 get192 {193 if (Context.Options.RecordVideoDir == null)194 {195 return null;196 }197 return ForceVideo();198 }199 set => _video = value as Video;200 }201 internal BrowserContext OwnedContext { get; set; }202 internal Dictionary<string, Delegate> Bindings { get; } = new();203 internal List<Worker> WorkersList { get; } = new();204 internal Page Opener => _initializer.Opener;205 internal PageChannel Channel => _channel;206 internal float DefaultTimeout207 {208 get => _defaultTimeout;209 set210 {211 _defaultTimeout = value;212 _channel.SetDefaultTimeoutNoReplyAsync(value).IgnoreException();213 }214 }215 internal float DefaultNavigationTimeout216 {217 get => _defaultNavigationTimeout;218 set219 {220 _defaultNavigationTimeout = value;221 _channel.SetDefaultNavigationTimeoutNoReplyAsync(value).IgnoreException();222 }223 }224 internal TaskCompletionSource<bool> ClosedOrCrashedTcs { get; } = new();225 public IFrame Frame(string name)226 => Frames.FirstOrDefault(f => f.Name == name);227 public IFrame FrameByUrl(string urlString) => Frames.FirstOrDefault(f => Context.UrlMatches(urlString, f.Url));228 public IFrame FrameByUrl(Regex urlRegex) => Frames.FirstOrDefault(f => urlRegex.IsMatch(f.Url));229 public IFrame FrameByUrl(Func<string, bool> urlFunc) => Frames.FirstOrDefault(f => urlFunc(f.Url));230 IFrameLocator IPage.FrameLocator(string selector) => MainFrame.FrameLocator(selector);231 public Task<string> TitleAsync() => MainFrame.TitleAsync();232 public Task BringToFrontAsync() => _channel.BringToFrontAsync();233 public Task<IPage> OpenerAsync() => Task.FromResult<IPage>(Opener?.IsClosed == false ? Opener : null);234 public Task EmulateMediaAsync(PageEmulateMediaOptions options = default)235 {236 var args = new Dictionary<string, object>237 {238 ["media"] = options?.Media,239 ["colorScheme"] = options?.ColorScheme,240 ["reducedMotion"] = options?.ReducedMotion,241 ["forcedColors"] = options?.ForcedColors,242 };243 return _channel.EmulateMediaAsync(args);244 }245 public Task<IResponse> GotoAsync(string url, PageGotoOptions options = default)246 => MainFrame.GotoAsync(url, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout, Referer = options?.Referer });247 public Task WaitForURLAsync(string url, PageWaitForURLOptions options = default)248 => MainFrame.WaitForURLAsync(url, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });249 public Task WaitForURLAsync(Regex url, PageWaitForURLOptions options = default)250 => MainFrame.WaitForURLAsync(url, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });251 public Task WaitForURLAsync(Func<string, bool> url, PageWaitForURLOptions options = default)252 => MainFrame.WaitForURLAsync(url, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });253 public Task<IConsoleMessage> WaitForConsoleMessageAsync(PageWaitForConsoleMessageOptions options = default)254 => InnerWaitForEventAsync(PageEvent.Console, null, options?.Predicate, options?.Timeout);255 public Task<IFileChooser> WaitForFileChooserAsync(PageWaitForFileChooserOptions options = default)256 => InnerWaitForEventAsync(PageEvent.FileChooser, null, options?.Predicate, options?.Timeout);257 public Task<IPage> WaitForPopupAsync(PageWaitForPopupOptions options = default)258 => InnerWaitForEventAsync(PageEvent.Popup, null, options?.Predicate, options?.Timeout);259 public Task<IWebSocket> WaitForWebSocketAsync(PageWaitForWebSocketOptions options = default)260 => InnerWaitForEventAsync(PageEvent.WebSocket, null, options?.Predicate, options?.Timeout);261 public Task<IWorker> WaitForWorkerAsync(PageWaitForWorkerOptions options = default)262 => InnerWaitForEventAsync(PageEvent.Worker, null, options?.Predicate, options?.Timeout);263 public Task<IResponse> WaitForNavigationAsync(PageWaitForNavigationOptions options = default)264 => MainFrame.WaitForNavigationAsync(new()265 {266 UrlString = options?.UrlString,267 UrlRegex = options?.UrlRegex,268 UrlFunc = options?.UrlFunc,269 WaitUntil = options?.WaitUntil,270 Timeout = options?.Timeout,271 });272 public Task<IResponse> RunAndWaitForNavigationAsync(Func<Task> action, PageRunAndWaitForNavigationOptions options = default)273 => MainFrame.RunAndWaitForNavigationAsync(action, new()274 {275 UrlString = options?.UrlString,276 UrlRegex = options?.UrlRegex,277 UrlFunc = options?.UrlFunc,278 WaitUntil = options?.WaitUntil,279 Timeout = options?.Timeout,280 });281 public Task<IRequest> WaitForRequestAsync(string urlOrPredicate, PageWaitForRequestOptions options = default)282 => InnerWaitForEventAsync(PageEvent.Request, null, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);283 public Task<IRequest> WaitForRequestAsync(Regex urlOrPredicate, PageWaitForRequestOptions options = default)284 => InnerWaitForEventAsync(PageEvent.Request, null, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);285 public Task<IRequest> WaitForRequestAsync(Func<IRequest, bool> urlOrPredicate, PageWaitForRequestOptions options = default)286 => InnerWaitForEventAsync(PageEvent.Request, null, e => urlOrPredicate(e), options?.Timeout);287 public Task<IRequest> WaitForRequestFinishedAsync(PageWaitForRequestFinishedOptions options = default)288 => InnerWaitForEventAsync(PageEvent.RequestFinished, null, options?.Predicate, options?.Timeout);289 public Task<IResponse> WaitForResponseAsync(string urlOrPredicate, PageWaitForResponseOptions options = default)290 => InnerWaitForEventAsync(PageEvent.Response, null, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);291 public Task<IResponse> WaitForResponseAsync(Regex urlOrPredicate, PageWaitForResponseOptions options = default)292 => InnerWaitForEventAsync(PageEvent.Response, null, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);293 public Task<IResponse> WaitForResponseAsync(Func<IResponse, bool> urlOrPredicate, PageWaitForResponseOptions options = default)294 => InnerWaitForEventAsync(PageEvent.Response, null, e => urlOrPredicate(e), options?.Timeout);295 public Task<IConsoleMessage> RunAndWaitForConsoleMessageAsync(Func<Task> action, PageRunAndWaitForConsoleMessageOptions options = default)296 => InnerWaitForEventAsync(PageEvent.Console, action, options?.Predicate, options?.Timeout);297 public Task<IDownload> WaitForDownloadAsync(PageWaitForDownloadOptions options = default)298 => InnerWaitForEventAsync(PageEvent.Download, null, options?.Predicate, options?.Timeout);299 public Task<IDownload> RunAndWaitForDownloadAsync(Func<Task> action, PageRunAndWaitForDownloadOptions options = default)300 => InnerWaitForEventAsync(PageEvent.Download, action, options?.Predicate, options?.Timeout);301 public Task<IFileChooser> RunAndWaitForFileChooserAsync(Func<Task> action, PageRunAndWaitForFileChooserOptions options = default)302 => InnerWaitForEventAsync(PageEvent.FileChooser, action, options?.Predicate, options?.Timeout);303 public Task<IPage> RunAndWaitForPopupAsync(Func<Task> action, PageRunAndWaitForPopupOptions options = default)304 => InnerWaitForEventAsync(PageEvent.Popup, action, options?.Predicate, options?.Timeout);305 public Task<IRequest> RunAndWaitForRequestFinishedAsync(Func<Task> action, PageRunAndWaitForRequestFinishedOptions options = default)306 => InnerWaitForEventAsync(PageEvent.RequestFinished, action, options?.Predicate, options?.Timeout);307 public Task<IWebSocket> RunAndWaitForWebSocketAsync(Func<Task> action, PageRunAndWaitForWebSocketOptions options = default)308 => InnerWaitForEventAsync(PageEvent.WebSocket, action, options?.Predicate, options?.Timeout);309 public Task<IWorker> RunAndWaitForWorkerAsync(Func<Task> action, PageRunAndWaitForWorkerOptions options = default)310 => InnerWaitForEventAsync(PageEvent.Worker, action, options?.Predicate, options?.Timeout);311 public Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, string urlOrPredicate, PageRunAndWaitForRequestOptions options = default)312 => InnerWaitForEventAsync(PageEvent.Request, action, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);313 public Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, Regex urlOrPredicate, PageRunAndWaitForRequestOptions options = default)314 => InnerWaitForEventAsync(PageEvent.Request, action, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);315 public Task<IRequest> RunAndWaitForRequestAsync(Func<Task> action, Func<IRequest, bool> urlOrPredicate, PageRunAndWaitForRequestOptions options = default)316 => InnerWaitForEventAsync(PageEvent.Request, action, e => urlOrPredicate(e), options?.Timeout);317 public Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, string urlOrPredicate, PageRunAndWaitForResponseOptions options = default)318 => InnerWaitForEventAsync(PageEvent.Response, action, e => Context.UrlMatches(e.Url, urlOrPredicate), options?.Timeout);319 public Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, Regex urlOrPredicate, PageRunAndWaitForResponseOptions options = default)320 => InnerWaitForEventAsync(PageEvent.Response, action, e => urlOrPredicate.IsMatch(e.Url), options?.Timeout);321 public Task<IResponse> RunAndWaitForResponseAsync(Func<Task> action, Func<IResponse, bool> urlOrPredicate, PageRunAndWaitForResponseOptions options = default)322 => InnerWaitForEventAsync(PageEvent.Response, action, e => urlOrPredicate(e), options?.Timeout);323 public Task<IJSHandle> WaitForFunctionAsync(string expression, object arg = default, PageWaitForFunctionOptions options = default)324 => MainFrame.WaitForFunctionAsync(expression, arg, new() { PollingInterval = options?.PollingInterval, Timeout = options?.Timeout });325 public async Task<T> InnerWaitForEventAsync<T>(PlaywrightEvent<T> pageEvent, Func<Task> action = default, Func<T, bool> predicate = default, float? timeout = default)326 {327 if (pageEvent == null)328 {329 throw new ArgumentException("Page event is required", nameof(pageEvent));330 }331 timeout ??= _defaultTimeout;332 using var waiter = new Waiter(this, $"page.WaitForEventAsync(\"{typeof(T)}\")");333 waiter.RejectOnTimeout(Convert.ToInt32(timeout), $"Timeout {timeout}ms exceeded while waiting for event \"{pageEvent.Name}\"");334 if (pageEvent.Name != PageEvent.Crash.Name)335 {336 waiter.RejectOnEvent<IPage>(this, PageEvent.Crash.Name, new("Page crashed"));337 }338 if (pageEvent.Name != PageEvent.Close.Name)339 {340 waiter.RejectOnEvent<IPage>(this, PageEvent.Close.Name, new("Page closed"));341 }342 var result = waiter.WaitForEventAsync(this, pageEvent.Name, predicate);343 if (action != null)344 {345 await WrapApiBoundaryAsync(() => Task.WhenAll(result, action())).ConfigureAwait(false);346 }347 return await result.ConfigureAwait(false);348 }349 public async Task CloseAsync(PageCloseOptions options = default)350 {351 try352 {353 await _channel.CloseAsync(options?.RunBeforeUnload ?? false).ConfigureAwait(false);354 if (OwnedContext != null)355 {356 await OwnedContext.CloseAsync().ConfigureAwait(false);357 }358 }359 catch (Exception e) when (DriverMessages.IsSafeCloseError(e))360 {361 // Swallow exception362 }363 }364 public Task<T> EvaluateAsync<T>(string expression, object arg) => MainFrame.EvaluateAsync<T>(expression, arg);365 public Task<JsonElement?> EvalOnSelectorAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync(selector, expression, arg);366 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, PageEvalOnSelectorOptions options = null)367 => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg, new() { Strict = options?.Strict });368 public ILocator Locator(string selector, PageLocatorOptions options = default)369 => MainFrame.Locator(selector, new() { HasTextString = options?.HasTextString, HasTextRegex = options?.HasTextRegex, Has = options?.Has });370 public Task<IElementHandle> QuerySelectorAsync(string selector, PageQuerySelectorOptions options = null)371 => MainFrame.QuerySelectorAsync(selector, new() { Strict = options?.Strict });372 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg);373 public Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync(selector, expression, arg);374 public Task<T> EvalOnSelectorAllAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync<T>(selector, expression, arg);375 public Task FillAsync(string selector, string value, PageFillOptions options = default)376 => MainFrame.FillAsync(selector, value, new() { NoWaitAfter = options?.NoWaitAfter, Timeout = options?.Timeout, Force = options?.Force, Strict = options?.Strict });377 public Task SetInputFilesAsync(string selector, string files, PageSetInputFilesOptions options = default)378 => MainFrame.SetInputFilesAsync(selector, files, Map(options));379 public Task SetInputFilesAsync(string selector, IEnumerable<string> files, PageSetInputFilesOptions options = default)380 => MainFrame.SetInputFilesAsync(selector, files, Map(options));381 public Task SetInputFilesAsync(string selector, FilePayload files, PageSetInputFilesOptions options = default)382 => MainFrame.SetInputFilesAsync(selector, files, Map(options));383 public Task SetInputFilesAsync(string selector, IEnumerable<FilePayload> files, PageSetInputFilesOptions options = default)384 => MainFrame.SetInputFilesAsync(selector, files, Map(options));385 public Task TypeAsync(string selector, string text, PageTypeOptions options = default)386 => MainFrame.TypeAsync(selector, text, new()387 {388 Delay = options?.Delay,389 NoWaitAfter = options?.NoWaitAfter,390 Timeout = options?.Timeout,391 Strict = options?.Strict,392 });393 public Task FocusAsync(string selector, PageFocusOptions options = default)394 => MainFrame.FocusAsync(selector, new()395 {396 Timeout = options?.Timeout,397 Strict = options?.Strict,398 });399 public Task HoverAsync(string selector, PageHoverOptions options = default)400 => MainFrame.HoverAsync(401 selector,402 new()403 {404 Position = options?.Position,405 Modifiers = options?.Modifiers,406 Force = options?.Force,407 Timeout = options?.Timeout,408 Trial = options?.Trial,409 Strict = options?.Strict,410 });411 public Task PressAsync(string selector, string key, PagePressOptions options = default)412 => MainFrame.PressAsync(selector, key, new()413 {414 Delay = options?.Delay,415 NoWaitAfter = options?.NoWaitAfter,416 Timeout = options?.Timeout,417 Strict = options?.Strict,418 });419 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, PageSelectOptionOptions options = default)420 => SelectOptionAsync(selector, new[] { values }, options);421 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, PageSelectOptionOptions options = default)422 => SelectOptionAsync(selector, values.Select(x => new SelectOptionValue() { Value = x }), options);423 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, PageSelectOptionOptions options = default)424 => SelectOptionAsync(selector, new[] { values }, options);425 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, PageSelectOptionOptions options = default)426 => MainFrame.SelectOptionAsync(selector, values, new()427 {428 NoWaitAfter = options?.NoWaitAfter,429 Timeout = options?.Timeout,430 Force = options?.Force,431 Strict = options?.Strict,432 });433 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, PageSelectOptionOptions options = default)434 => SelectOptionAsync(selector, new[] { values }, options);435 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, PageSelectOptionOptions options = default)436 => MainFrame.SelectOptionAsync(selector, values, new()437 {438 NoWaitAfter = options?.NoWaitAfter,439 Timeout = options?.Timeout,440 Force = options?.Force,441 Strict = options?.Strict,442 });443 public Task WaitForTimeoutAsync(float timeout) => MainFrame.WaitForTimeoutAsync(timeout);444 public Task<IElementHandle> WaitForSelectorAsync(string selector, PageWaitForSelectorOptions options = default)445 => MainFrame.WaitForSelectorAsync(selector, new()446 {447 State = options?.State,448 Timeout = options?.Timeout,449 Strict = options?.Strict,450 });451 public Task<JsonElement?> EvaluateAsync(string expression, object arg) => MainFrame.EvaluateAsync(expression, arg);452 public async Task<byte[]> ScreenshotAsync(PageScreenshotOptions options = default)453 {454 options ??= new PageScreenshotOptions();455 if (options.Type == null && !string.IsNullOrEmpty(options.Path))456 {457 options.Type = ElementHandle.DetermineScreenshotType(options.Path);458 }459 byte[] result = await _channel.ScreenshotAsync(460 path: options.Path,461 fullPage: options.FullPage,462 clip: options.Clip,463 omitBackground: options.OmitBackground,464 type: options.Type,465 quality: options.Quality,466 mask: options.Mask,467 animations: options.Animations,468 caret: options.Caret,469 scale: options.Scale,470 timeout: options.Timeout).ConfigureAwait(false);471 if (!string.IsNullOrEmpty(options.Path))472 {473 Directory.CreateDirectory(new FileInfo(options.Path).Directory.FullName);474 File.WriteAllBytes(options.Path, result);475 }476 return result;477 }478 public Task SetContentAsync(string html, PageSetContentOptions options = default)479 => MainFrame.SetContentAsync(html, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });480 public Task<string> ContentAsync() => MainFrame.ContentAsync();481 public Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)482 => _channel.SetExtraHTTPHeadersAsync(headers);483 public Task<IElementHandle> QuerySelectorAsync(string selector) => MainFrame.QuerySelectorAsync(selector);484 public Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)485 => MainFrame.QuerySelectorAllAsync(selector);486 public Task<IJSHandle> EvaluateHandleAsync(string expression, object arg) => MainFrame.EvaluateHandleAsync(expression, arg);487 public Task<IElementHandle> AddScriptTagAsync(PageAddScriptTagOptions options = default)488 => MainFrame.AddScriptTagAsync(new()489 {490 Url = options?.Url,491 Path = options?.Path,492 Content = options?.Content,493 Type = options?.Type,494 });495 public Task<IElementHandle> AddStyleTagAsync(PageAddStyleTagOptions options = default)496 => MainFrame.AddStyleTagAsync(new()497 {498 Url = options?.Url,499 Path = options?.Path,500 Content = options?.Content,501 });502 public Task ClickAsync(string selector, PageClickOptions options = default)503 => MainFrame.ClickAsync(504 selector,505 new()506 {507 Button = options?.Button,508 ClickCount = options?.ClickCount,509 Delay = options?.Delay,510 Position = options?.Position,511 Modifiers = options?.Modifiers,512 Force = options?.Force,513 NoWaitAfter = options?.NoWaitAfter,514 Timeout = options?.Timeout,515 Trial = options?.Trial,516 Strict = options?.Strict,517 });518 public Task DblClickAsync(string selector, PageDblClickOptions options = default)519 => MainFrame.DblClickAsync(selector, new()520 {521 Delay = options?.Delay,522 Button = options?.Button,523 Position = options?.Position,524 Modifiers = options?.Modifiers,525 Timeout = options?.Timeout,526 Force = options?.Force,527 NoWaitAfter = options?.NoWaitAfter,528 Trial = options?.Trial,529 Strict = options?.Strict,530 });531 public async Task<IResponse> GoBackAsync(PageGoBackOptions options = default)532 => (await _channel.GoBackAsync(options?.Timeout, options?.WaitUntil).ConfigureAwait(false))?.Object;533 public async Task<IResponse> GoForwardAsync(PageGoForwardOptions options = default)534 => (await _channel.GoForwardAsync(options?.Timeout, options?.WaitUntil).ConfigureAwait(false))?.Object;535 public async Task<IResponse> ReloadAsync(PageReloadOptions options = default)536 => (await _channel.ReloadAsync(options?.Timeout, options?.WaitUntil).ConfigureAwait(false))?.Object;537 public Task ExposeBindingAsync(string name, Action callback, PageExposeBindingOptions options = default)538 => InnerExposeBindingAsync(name, (Delegate)callback, options?.Handle ?? false);539 public Task ExposeBindingAsync(string name, Action<BindingSource> callback)540 => InnerExposeBindingAsync(name, (Delegate)callback);541 public Task ExposeBindingAsync<T>(string name, Action<BindingSource, T> callback)542 => InnerExposeBindingAsync(name, (Delegate)callback);543 public Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, TResult> callback)544 => InnerExposeBindingAsync(name, (Delegate)callback);545 public Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, IJSHandle, TResult> callback)546 => InnerExposeBindingAsync(name, (Delegate)callback, true);547 public Task ExposeBindingAsync<T, TResult>(string name, Func<BindingSource, T, TResult> callback)548 => InnerExposeBindingAsync(name, (Delegate)callback);549 public Task ExposeBindingAsync<T1, T2, TResult>(string name, Func<BindingSource, T1, T2, TResult> callback)550 => InnerExposeBindingAsync(name, (Delegate)callback);551 public Task ExposeBindingAsync<T1, T2, T3, TResult>(string name, Func<BindingSource, T1, T2, T3, TResult> callback)552 => InnerExposeBindingAsync(name, (Delegate)callback);553 public Task ExposeBindingAsync<T1, T2, T3, T4, TResult>(string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback)554 => InnerExposeBindingAsync(name, (Delegate)callback);555 public Task ExposeFunctionAsync(string name, Action callback)556 => ExposeBindingAsync(name, (BindingSource _) => callback());557 public Task ExposeFunctionAsync<T>(string name, Action<T> callback)558 => ExposeBindingAsync(name, (BindingSource _, T t) => callback(t));559 public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> callback)560 => ExposeBindingAsync(name, (BindingSource _) => callback());561 public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> callback)562 => ExposeBindingAsync(name, (BindingSource _, T t) => callback(t));563 public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> callback)564 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2) => callback(t1, t2));565 public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> callback)566 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2, T3 t3) => callback(t1, t2, t3));567 public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> callback)568 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2, T3 t3, T4 t4) => callback(t1, t2, t3, t4));569 public async Task<byte[]> PdfAsync(PagePdfOptions options = default)570 {571 if (!Context.IsChromium)572 {573 throw new NotSupportedException("This browser doesn't support this action.");574 }575 byte[] result = await _channel.PdfAsync(576 scale: options?.Scale,577 displayHeaderFooter: options?.DisplayHeaderFooter,578 headerTemplate: options?.HeaderTemplate,579 footerTemplate: options?.FooterTemplate,580 printBackground: options?.PrintBackground,581 landscape: options?.Landscape,582 pageRanges: options?.PageRanges,583 format: options?.Format,584 width: options?.Width,585 height: options?.Height,586 margin: options?.Margin,587 preferCSSPageSize: options?.PreferCSSPageSize).ConfigureAwait(false);588 if (!string.IsNullOrEmpty(options?.Path))589 {590 Directory.CreateDirectory(new FileInfo(options.Path).Directory.FullName);591 File.WriteAllBytes(options.Path, result);592 }593 return result;594 }595 public Task AddInitScriptAsync(string script, string scriptPath)596 => _channel.AddInitScriptAsync(ScriptsHelper.EvaluationScript(script, scriptPath));597 public Task RouteAsync(string url, Action<IRoute> handler, PageRouteOptions options = null)598 => RouteAsync(new Regex(Context.CombineUrlWithBase(url).GlobToRegex()), null, handler, options);599 public Task RouteAsync(Regex url, Action<IRoute> handler, PageRouteOptions options = null)600 => RouteAsync(url, null, handler, options);601 public Task RouteAsync(Func<string, bool> url, Action<IRoute> handler, PageRouteOptions options = null)602 => RouteAsync(null, url, handler, options);603 public Task UnrouteAsync(string urlString, Action<IRoute> handler)604 => UnrouteAsync(new Regex(Context.CombineUrlWithBase(urlString).GlobToRegex()), null, handler);605 public Task UnrouteAsync(Regex urlString, Action<IRoute> handler)606 => UnrouteAsync(urlString, null, handler);607 public Task UnrouteAsync(Func<string, bool> urlFunc, Action<IRoute> handler)608 => UnrouteAsync(null, urlFunc, handler);609 public Task WaitForLoadStateAsync(LoadState? state = default, PageWaitForLoadStateOptions options = default)610 => MainFrame.WaitForLoadStateAsync(state, new() { Timeout = options?.Timeout });611 public Task SetViewportSizeAsync(int width, int height)612 {613 ViewportSize = new() { Width = width, Height = height };614 return _channel.SetViewportSizeAsync(ViewportSize);615 }616 public Task SetCheckedAsync(string selector, bool checkedState, PageSetCheckedOptions options = null)617 => checkedState ?618 MainFrame.CheckAsync(selector, new()619 {620 Position = options?.Position,621 Force = options?.Force,622 NoWaitAfter = options?.NoWaitAfter,623 Strict = options?.Strict,624 Timeout = options?.Timeout,625 Trial = options?.Trial,626 })627 : MainFrame.UncheckAsync(selector, new()628 {629 Position = options?.Position,630 Force = options?.Force,631 NoWaitAfter = options?.NoWaitAfter,632 Timeout = options?.Timeout,633 Trial = options?.Trial,634 Strict = options?.Strict,635 });636 public Task CheckAsync(string selector, PageCheckOptions options = default)637 => MainFrame.CheckAsync(selector, new()638 {639 Position = options?.Position,640 Force = options?.Force,641 NoWaitAfter = options?.NoWaitAfter,642 Strict = options?.Strict,643 Timeout = options?.Timeout,644 Trial = options?.Trial,645 });646 public Task UncheckAsync(string selector, PageUncheckOptions options = default)647 => MainFrame.UncheckAsync(selector, new()648 {649 Position = options?.Position,650 Force = options?.Force,651 NoWaitAfter = options?.NoWaitAfter,652 Timeout = options?.Timeout,653 Trial = options?.Trial,654 Strict = options?.Strict,655 });656 public Task DispatchEventAsync(string selector, string type, object eventInit = default, PageDispatchEventOptions options = default)657 => MainFrame.DispatchEventAsync(selector, type, eventInit, new() { Timeout = options?.Timeout, Strict = options?.Strict });658 public Task<string> GetAttributeAsync(string selector, string name, PageGetAttributeOptions options = default)659 => MainFrame.GetAttributeAsync(selector, name, new()660 {661 Timeout = options?.Timeout,662 Strict = options?.Strict,663 });664 public Task<string> InnerHTMLAsync(string selector, PageInnerHTMLOptions options = default)665 => MainFrame.InnerHTMLAsync(selector, new()666 {667 Timeout = options?.Timeout,668 Strict = options?.Strict,669 });670 public Task<string> InnerTextAsync(string selector, PageInnerTextOptions options = default)671 => MainFrame.InnerTextAsync(selector, new()672 {673 Timeout = options?.Timeout,674 Strict = options?.Strict,675 });676 public Task<string> TextContentAsync(string selector, PageTextContentOptions options = default)677 => MainFrame.TextContentAsync(selector, new()678 {679 Timeout = options?.Timeout,680 Strict = options?.Strict,681 });682 public Task TapAsync(string selector, PageTapOptions options = default)683 => MainFrame.TapAsync(684 selector,685 new()686 {687 Modifiers = options?.Modifiers,688 Position = options?.Position,689 Force = options?.Force,690 NoWaitAfter = options?.NoWaitAfter,691 Timeout = options?.Timeout,692 Trial = options?.Trial,693 Strict = options?.Strict,694 });695 public Task<bool> IsCheckedAsync(string selector, PageIsCheckedOptions options = default)696 => MainFrame.IsCheckedAsync(selector, new()697 {698 Timeout = options?.Timeout,699 Strict = options?.Strict,700 });701 public Task<bool> IsDisabledAsync(string selector, PageIsDisabledOptions options = default)702 => MainFrame.IsDisabledAsync(selector, new()703 {704 Timeout = options?.Timeout,705 Strict = options?.Strict,706 });707 public Task<bool> IsEditableAsync(string selector, PageIsEditableOptions options = default)708 => MainFrame.IsEditableAsync(selector, new()709 {710 Timeout = options?.Timeout,711 Strict = options?.Strict,712 });713 public Task<bool> IsEnabledAsync(string selector, PageIsEnabledOptions options = default)714 => MainFrame.IsEnabledAsync(selector, new()715 {716 Timeout = options?.Timeout,717 Strict = options?.Strict,718 });719#pragma warning disable CS0612 // Type or member is obsolete720 public Task<bool> IsHiddenAsync(string selector, PageIsHiddenOptions options = default)721 => MainFrame.IsHiddenAsync(selector, new()722 {723 Timeout = options?.Timeout,724 Strict = options?.Strict,725 });726 public Task<bool> IsVisibleAsync(string selector, PageIsVisibleOptions options = default)727 => MainFrame.IsVisibleAsync(selector, new()728 {729 Timeout = options?.Timeout,730 Strict = options?.Strict,731 });732#pragma warning restore CS0612 // Type or member is obsolete733 public Task PauseAsync() => Context.Channel.PauseAsync();734 public void SetDefaultNavigationTimeout(float timeout) => DefaultNavigationTimeout = timeout;735 public void SetDefaultTimeout(float timeout) => DefaultTimeout = timeout;736 public Task<string> InputValueAsync(string selector, PageInputValueOptions options = null)737 => MainFrame.InputValueAsync(selector, new()738 {739 Timeout = options?.Timeout,740 Strict = options?.Strict,741 });742 public Task DragAndDropAsync(string source, string target, PageDragAndDropOptions options = null)743 => MainFrame.DragAndDropAsync(source, target, new()744 {745 Force = options?.Force,746 NoWaitAfter = options?.NoWaitAfter,747 Timeout = options?.Timeout,748 Trial = options?.Trial,749 Strict = options?.Strict,750 });751 internal void NotifyPopup(Page page) => Popup?.Invoke(this, page);752 internal void OnFrameNavigated(Frame frame)753 => FrameNavigated?.Invoke(this, frame);754 internal void FireRequest(IRequest request) => Request?.Invoke(this, request);755 internal void FireRequestFailed(IRequest request) => RequestFailed?.Invoke(this, request);756 internal void FireRequestFinished(IRequest request) => RequestFinished?.Invoke(this, request);757 internal void FireResponse(IResponse response) => Response?.Invoke(this, response);758 private Task RouteAsync(Regex urlRegex, Func<string, bool> urlFunc, Action<IRoute> handler, PageRouteOptions options)759 => RouteAsync(new()760 {761 Regex = urlRegex,762 Function = urlFunc,763 Handler = handler,764 Times = options?.Times,765 });766 private Task RouteAsync(RouteSetting setting)767 {768 _routes.Insert(0, setting);769 if (_routes.Count == 1)770 {771 return _channel.SetNetworkInterceptionEnabledAsync(true);772 }773 return Task.CompletedTask;774 }775 private Task UnrouteAsync(Regex urlRegex, Func<string, bool> urlFunc, Action<IRoute> handler = null)776 => UnrouteAsync(new()777 {778 Function = urlFunc,779 Regex = urlRegex,780 Handler = handler,781 });782 private Task UnrouteAsync(RouteSetting setting)783 {784 var newRoutesList = new List<RouteSetting>();785 newRoutesList.AddRange(_routes.Where(r =>786 (setting.Regex != null && !(r.Regex == setting.Regex || (r.Regex.ToString() == setting.Regex.ToString() && r.Regex.Options == setting.Regex.Options))) ||787 (setting.Function != null && r.Function != setting.Function) ||788 (setting.Handler != null && r.Handler != setting.Handler)));789 _routes = newRoutesList;790 if (_routes.Count == 0)791 {792 return DisableInterceptionAsync();793 }794 return Task.CompletedTask;795 }796 internal void OnClose()797 {798 IsClosed = true;799 Context?.PagesList.Remove(this);800 RejectPendingOperations(false);801 Close?.Invoke(this, this);802 }803 private void Channel_Crashed(object sender, EventArgs e)804 {805 RejectPendingOperations(true);806 Crash?.Invoke(this, this);807 }808 private void Channel_BindingCall(object sender, BindingCallEventArgs e)809 {810 if (Bindings.TryGetValue(e.BindingCall.Name, out var binding))811 {812 _ = e.BindingCall.CallAsync(binding);813 }814 }815 private void OnRoute(Route route, IRequest request)816 {817 foreach (var routeHandler in _routes.ToList())818 {819 if ((routeHandler.Regex?.IsMatch(request.Url) == true) ||820 (routeHandler.Function?.Invoke(request.Url) == true))821 {822 try823 {824 routeHandler.Handle(route);825 }826 finally827 {828 if (!routeHandler.IsActive())829 {830 _routes.Remove(routeHandler);831 if (_routes.Count == 0)832 {833 DisableInterceptionAsync().ConfigureAwait(false);834 }835 }836 }837 return;838 }839 }840 Context.OnRoute(route, request);841 }842 internal async Task DisableInterceptionAsync()843 {844 await Channel.SetNetworkInterceptionEnabledAsync(false).ConfigureAwait(false);845 }846 private void Channel_FrameDetached(object sender, IFrame args)847 {848 var frame = (Frame)args;849 _frames.Remove(frame);850 frame.IsDetached = true;851 frame.ParentFrame?.ChildFramesList?.Remove(frame);852 FrameDetached?.Invoke(this, args);853 }854 private void Channel_FrameAttached(object sender, IFrame args)...

Full Screen

Full Screen

BrowserContext.cs

Source:BrowserContext.cs Github

copy

Full Screen

...246 => InnerWaitForEventAsync(BrowserContextEvent.Page, action, options?.Predicate, options?.Timeout);247 public ValueTask DisposeAsync() => new ValueTask(CloseAsync());248 public void SetDefaultNavigationTimeout(float timeout) => DefaultNavigationTimeout = timeout;249 public void SetDefaultTimeout(float timeout) => DefaultTimeout = timeout;250 internal void OnRoute(Route route, IRequest request)251 {252 foreach (var routeHandler in _routes)253 {254 if (255 routeHandler.Regex?.IsMatch(request.Url) == true ||256 routeHandler.Function?.Invoke(request.Url) == true)257 {258 try259 {260 routeHandler.Handle(route);261 }262 finally263 {264 if (!routeHandler.IsActive())265 {266 _routes.Remove(routeHandler);267 if (_routes.Count == 0)268 {269 DisableInterceptionAsync().ConfigureAwait(false);270 }271 }272 }273 return;274 }275 }276 route.ContinueAsync().IgnoreException();277 }278 internal async Task DisableInterceptionAsync()279 {280 await Channel.SetNetworkInterceptionEnabledAsync(false).ConfigureAwait(false);281 }282 internal bool UrlMatches(string url, string glob)283 => new Regex(CombineUrlWithBase(glob).GlobToRegex()).Match(url).Success;284 internal string CombineUrlWithBase(string url)285 {286 var baseUrl = Options?.BaseURL;287 if (string.IsNullOrEmpty(baseUrl)288 || (url?.StartsWith("*", StringComparison.InvariantCultureIgnoreCase) ?? false)289 || !Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))290 {291 return url;292 }293 var mUri = new Uri(url, UriKind.RelativeOrAbsolute);294 if (!mUri.IsAbsoluteUri)295 {296 return new Uri(new Uri(baseUrl), mUri).ToString();297 }298 return url;299 }300 private Task RouteAsync(Regex urlRegex, Func<string, bool> urlFunc, Action<IRoute> handler, BrowserContextRouteOptions options)301 => RouteAsync(new()302 {303 Regex = urlRegex,304 Function = urlFunc,305 Handler = handler,306 Times = options?.Times,307 });308 private Task RouteAsync(RouteSetting setting)309 {310 _routes.Insert(0, setting);311 if (_routes.Count == 1)312 {313 return Channel.SetNetworkInterceptionEnabledAsync(true);314 }315 return Task.CompletedTask;316 }317 private Task UnrouteAsync(Regex urlRegex, Func<string, bool> urlFunc, Action<IRoute> handler = null)318 => UnrouteAsync(new()319 {320 Function = urlFunc,321 Regex = urlRegex,322 Handler = handler,323 });324 private Task UnrouteAsync(RouteSetting setting)325 {326 var newRoutesList = new List<RouteSetting>();327 newRoutesList.AddRange(_routes.Where(r =>328 (setting.Regex != null && !(r.Regex == setting.Regex || (r.Regex.ToString() == setting.Regex.ToString() && r.Regex.Options == setting.Regex.Options))) ||329 (setting.Function != null && r.Function != setting.Function) ||330 (setting.Handler != null && r.Handler != setting.Handler)));331 _routes = newRoutesList;332 if (_routes.Count == 0)333 {334 return Channel.SetNetworkInterceptionEnabledAsync(false);335 }336 return Task.CompletedTask;337 }338 internal void OnClose()339 {340 if (Browser != null)341 {342 ((Browser)Browser).BrowserContextsList.Remove(this);343 }344 Close?.Invoke(this, this);345 _closeTcs.TrySetResult(true);346 }347 private void Channel_OnPage(object sender, BrowserContextPageEventArgs e)348 {349 var page = e.PageChannel.Object;350 page.Context = this;351 PagesList.Add(page);352 Page?.Invoke(this, page);353 if (page.Opener?.IsClosed == false)354 {355 page.Opener.NotifyPopup(page);356 }357 }358 private void Channel_BindingCall(object sender, BindingCallEventArgs e)359 {360 if (_bindings.TryGetValue(e.BindingCall.Name, out var binding))361 {362 _ = e.BindingCall.CallAsync(binding);363 }364 }365 private void Channel_Route(object sender, RouteEventArgs e) => OnRoute(e.Route, e.Request);366 private Task ExposeBindingAsync(string name, Delegate callback, bool handle = false)367 {368 foreach (var page in PagesList)369 {370 if (page.Bindings.ContainsKey(name))371 {372 throw new PlaywrightException($"Function \"{name}\" has been already registered in one of the pages");373 }374 }375 if (_bindings.ContainsKey(name))376 {377 throw new PlaywrightException($"Function \"{name}\" has been already registered");378 }379 _bindings.Add(name, callback);...

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync(new BrowserNewContextOptions13 {14 });15 context.Route("**/api/GetProduct", (route, request) =>16 {17 route.FulfillAsync(new RouteFulfillOptions18 {19 Body = "{ \"product\": \"Playwright\" }"20 });21 });22 var page = await context.NewPageAsync();23 await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);24 await page.ClickAsync("text=GetProduct");25 await page.WaitForTimeoutAsync(5000);26 }27 }28}29using System;30using System.Threading.Tasks;31using Microsoft.Playwright;32{33 {34 static async Task Main(string[] args)35 {36 using var playwright = await Playwright.CreateAsync();37 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions38 {39 });40 var context = await browser.NewContextAsync(new BrowserNewContextOptions41 {42 });43 context.Request += (sender, e) =>44 {45 Console.WriteLine(e.Request.Url);46 };47 var page = await context.NewPageAsync();48 await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);49 await page.ClickAsync("text=GetProduct");50 await page.WaitForTimeoutAsync(5000);51 }52 }53}54using System;55using System.Threading.Tasks;56using Microsoft.Playwright;57{58 {59 static async Task Main(string[] args)60 {

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var context = await browser.NewContextAsync();11 context.Route("**/*", route => {12 Console.WriteLine("Request intercepted");13 route.ContinueAsync();14 });15 var page = await context.NewPageAsync();16 Console.WriteLine("Press any key to exit");17 Console.ReadKey();18 }19 }20}

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1var playwright = await Microsoft.Playwright.Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(new Microsoft.Playwright.LaunchOptions { Headless = false });3var context = await browser.NewContextAsync();4await context.RouteAsync("**/*", route => {5 Console.WriteLine(route.Request.Url);6 route.ContinueAsync();7});8var page = await context.NewPageAsync();9await page.ClickAsync("text=English");10await page.ClickAsync("text=Español");11await page.ClickAsync("text=日本語");12await page.ClickAsync("text=Deutsch");13await page.ClickAsync("text=Русский");14await page.ClickAsync("text=Français");15await page.ClickAsync("text=Italiano");16await page.ClickAsync("text=中文");17await page.ClickAsync("text=Português");18await page.ClickAsync("text=Polski");19await page.ClickAsync("text=한국어");20await page.ClickAsync("text=Nederlands");21await page.ClickAsync("text=Čeština");22await page.ClickAsync("text=العربية");23await page.ClickAsync("text=हिन्दी");24await page.ClickAsync("text=ไทย");25await page.ClickAsync("text=Tiếng Việt");26await page.ClickAsync("text=فارسی");27await page.ClickAsync("text=Magyar");28await page.ClickAsync("text=עברית");29await page.ClickAsync("text=తెలుగు");30await page.ClickAsync("text=Română");31await page.ClickAsync("text=日本語");32await page.ClickAsync("text=Українська");33await page.ClickAsync("text=Български");34await page.ClickAsync("text=Беларуская");35await page.ClickAsync("text=العربية");36await page.ClickAsync("text=Azərbaycan");37await page.ClickAsync("text=Bahasa Indonesia");38await page.ClickAsync("text=Bahasa Melayu");39await page.ClickAsync("text=Català");40await page.ClickAsync("text=Čeština");41await page.ClickAsync("text=Deutsch");42await page.ClickAsync("text=Español

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System;3using System.IO;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions11 {12 });13 var context = await browser.NewContextAsync(new Browser.NewContextOptions14 {15 {16 {17 }18 }19 });20 var page = await context.NewPageAsync();21 await page.RouteAsync("**/*", route => route.ContinueAsync());22 await page.ClickAsync("text=Sign in");23 await page.TypeAsync("input[name=\"identifier\"]", "

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright; 2using System; 3using System.Threading.Tasks; 4{ 5 { 6 static async Task Main(string[] args) 7 { 8 using var playwright = await Playwright.CreateAsync(); 9 using var browser = await playwright.Chromium.LaunchAsync(); 10 var context = await browser.NewContextAsync(); 11 var page = await context.NewPageAsync(); 12 await page.ClickAsync("text=Sign in"); 13 await page.WaitForRequestAsync("**/api/v1/login"); 14 await page.WaitForResponseAsync("**/api/v1/login"); 15 await context.CloseAsync(); 16 await browser.CloseAsync(); 17 } 18 } 19}20using Microsoft.Playwright; 21using System; 22using System.Threading.Tasks; 23{ 24 { 25 static async Task Main(string[] args) 26 { 27 using var playwright = await Playwright.CreateAsync(); 28 using var browser = await playwright.Chromium.LaunchAsync(); 29 var context = await browser.NewContextAsync(); 30 var page = await context.NewPageAsync(); 31 await page.ClickAsync("text=Sign in"); 32 await page.WaitForRequestAsync("**/api/v1/login"); 33 await page.WaitForResponseAsync("**/api/v1/login"); 34 await context.CloseAsync(); 35 await browser.CloseAsync(); 36 } 37 } 38}39using Microsoft.Playwright; 40using System; 41using System.Threading.Tasks; 42{ 43 { 44 static async Task Main(string[] args) 45 { 46 using var playwright = await Playwright.CreateAsync(); 47 using var browser = await playwright.Chromium.LaunchAsync(); 48 var context = await browser.NewContextAsync(); 49 var page = await context.NewPageAsync(); 50 await page.ClickAsync("text=Sign in"); 51 await page.WaitForRequestAsync("**

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Core;2using Microsoft.Playwright.Core.Tests;3using NUnit.Framework;4using System;5using System.Collections.Generic;6using System.Linq;7using System.Text;8using System.Threading.Tasks;9{10 {11 public async Task ShouldWork()12 {13 await Page.GotoAsync(TestConstants.EmptyPage);14 var requests = new List<Request>();15 await Page.Context.OnRoute("**/*", (route, request) =>16 {17 requests.Add(request);18 route.ContinueAsync();19 });20 await Task.WhenAll(21 Page.GotoAsync(TestConstants.EmptyPage),22 Page.GotoAsync(TestConstants.EmptyPage),23 Page.GotoAsync(TestConstants.EmptyPage)24 );25 Assert.AreEqual(3, requests.Count);26 }27 }28}29using Microsoft.Playwright.Core;30using Microsoft.Playwright.Core.Tests;31using NUnit.Framework;32using System;33using System.Collections.Generic;34using System.Linq;35using System.Text;36using System.Threading.Tasks;37{38 {39 public async Task ShouldWork()40 {41 await Page.GotoAsync(TestConstants.EmptyPage);42 var requests = new List<Request>();43 await Page.Context.OnRoute("**/*", (route, request) =>44 {45 requests.Add(request);46 route.ContinueAsync();47 });48 await Task.WhenAll(49 Page.GotoAsync(TestConstants.EmptyPage),50 Page.GotoAsync(TestConstants.EmptyPage),51 Page.GotoAsync(TestConstants.EmptyPage)52 );53 Assert.AreEqual(3, requests.Count);54 }55 }56}57I am using the latest version of PlaywrightSharp (0.191.2) and the latest version of Microsoft.Playwright.Core (0

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1await using var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(headless: false);3var context = await browser.NewContextAsync();4await context.RouteAsync("**/*", async route =>5{6 var request = route.Request;7 var response = route.Response;8 Console.WriteLine($"Request: {request.Method} {request.Url}");9 if (response != null)10 {11 Console.WriteLine($"Response: {response.Status} {response.Url}");12 }13 await route.ContinueAsync();14});15var page = await context.NewPageAsync();16await page.CloseAsync();17await context.CloseAsync();18await browser.CloseAsync();

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Core;2using System;3using System.Collections.Generic;4using System.Text;5using System.Threading.Tasks;6{7 {8 public static async Task OnRoute(BrowserContext context)9 {10 await context.RouteAsync("**/*", route =>11 {12 var request = route.Request;13 Console.WriteLine(request.Url);14 route.ContinueAsync();15 return Task.CompletedTask;16 });17 }18 }19}20using Microsoft.Playwright.Core;21using System;22using System.Collections.Generic;23using System.Text;24using System.Threading.Tasks;25{26 {27 public static async Task OnRoute(BrowserContext context)28 {29 await context.RouteAsync("**/*", route =>30 {31 var request = route.Request;32 Console.WriteLine(request.Url);33 route.ContinueAsync();34 return Task.CompletedTask;35 });36 }37 }38}39using Microsoft.Playwright.Core;40using System;41using System.Collections.Generic;42using System.Text;43using System.Threading.Tasks;44{45 {46 public static async Task OnRoute(BrowserContext context)47 {48 await context.RouteAsync("**/*", route =>49 {50 var request = route.Request;51 Console.WriteLine(request.Url);52 route.ContinueAsync();53 return Task.CompletedTask;54 });55 }56 }57}58using Microsoft.Playwright.Core;59using System;60using System.Collections.Generic;61using System.Text;62using System.Threading.Tasks;63{64 {65 public static async Task OnRoute(BrowserContext context)66 {67 await context.RouteAsync("**/*", route =>68 {69 var request = route.Request;70 Console.WriteLine(request.Url);71 route.ContinueAsync();72 return Task.CompletedTask;73 });74 }75 }76}

Full Screen

Full Screen

OnRoute

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync(new BrowserNewContextOptions13 {14 });15 var page = await context.NewPageAsync();16 await page.SetContentAsync("<html><body><h1>Hello World!</h1></body></html>");17 await page.RouteAsync("**", route =>18 {19 if (route.Request.Url.Contains("Hello World!"))20 {21 route.FulfillAsync(new RouteFulfillOptions22 {23 });24 }25 {26 route.ContinueAsync();27 }28 });29 await page.SetContentAsync("<html><body><h1>Hello World!</h1></body></html>");30 await page.ContentAsync();31 await page.ScreenshotAsync("HelloWorld.png");32 await page.ContentAsync();33 await page.ScreenshotAsync("HelloWorldModified.png");34 }35 }36}37using System;38using System.Threading.Tasks;39using Microsoft.Playwright;40{41 {

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful