Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.RouteSetting
Page.cs
Source:Page.cs
...47 private readonly IMouse _mouse;48 private readonly IKeyboard _keyboard;49 private readonly ITouchscreen _touchscreen;50 private readonly PageInitializer _initializer;51 private List<RouteSetting> _routes = new();52 private EventHandler<IFileChooser> _fileChooserEventHandler;53 private bool _fileChooserIntercepted;54 private Video _video;55 private float _defaultNavigationTimeout;56 private float _defaultTimeout;57 internal Page(IChannelOwner parent, string guid, PageInitializer initializer) : base(parent, guid)58 {59 Context = (BrowserContext)parent;60 _channel = new(guid, parent.Connection, this);61 MainFrame = initializer.MainFrame;62 MainFrame.Page = this;63 _frames.Add(MainFrame);64 if (initializer.ViewportSize != null)65 {66 ViewportSize = new() { Width = initializer.ViewportSize.Width, Height = initializer.ViewportSize.Height };67 }68 IsClosed = initializer.IsClosed;69 _accessibility = new Accessibility(_channel);70 _keyboard = new Keyboard(_channel);71 _touchscreen = new Touchscreen(_channel);72 _mouse = new Mouse(_channel);73 _channel.Closed += (_, _) => OnClose();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;...
BrowserContext.cs
Source:BrowserContext.cs
...41 private readonly TaskCompletionSource<bool> _closeTcs = new();42 private readonly Dictionary<string, Delegate> _bindings = new();43 private readonly BrowserContextInitializer _initializer;44 private readonly ITracing _tracing;45 private List<RouteSetting> _routes = new();46 private float? _defaultNavigationTimeout;47 private float? _defaultTimeout;48 internal BrowserContext(IChannelOwner parent, string guid, BrowserContextInitializer initializer) : base(parent, guid)49 {50 Channel = new(guid, parent.Connection, this);51 Channel.Close += (_, _) => OnClose();52 Channel.Page += Channel_OnPage;53 Channel.BindingCall += Channel_BindingCall;54 Channel.Route += Channel_Route;55 Channel.RequestFailed += (_, e) =>56 {57 e.Request.Failure = e.FailureText;58 e.Request.Timing.ResponseEnd = e.ResponseEndTiming;59 RequestFailed?.Invoke(this, e.Request);60 e.Page?.FireRequestFailed(e.Request);61 e.Response?.ReportFinished(e.FailureText);62 };63 Channel.Request += (_, e) =>64 {65 Request?.Invoke(this, e.Request);66 e.Page?.FireRequest(e.Request);67 };68 Channel.RequestFinished += (_, e) =>69 {70 e.Request.Timing.ResponseEnd = e.ResponseEndTiming;71 e.Request.Sizes = e.RequestSizes;72 RequestFinished?.Invoke(this, e.Request);73 e.Page?.FireRequestFinished(e.Request);74 e.Response?.ReportFinished();75 };76 Channel.Response += (_, e) =>77 {78 Response?.Invoke(this, e.Response);79 e.Page?.FireResponse(e.Response);80 };81 _tracing = initializer.Tracing;82 _initializer = initializer;83 Browser = parent as IBrowser;84 }85 public event EventHandler<IBrowserContext> Close;86 public event EventHandler<IPage> Page;87 public event EventHandler<IRequest> Request;88 public event EventHandler<IRequest> RequestFailed;89 public event EventHandler<IRequest> RequestFinished;90 public event EventHandler<IResponse> Response;91 public ITracing Tracing92 {93 get => _tracing;94 set => throw new NotSupportedException();95 }96 ChannelBase IChannelOwner.Channel => Channel;97 IChannel<BrowserContext> IChannelOwner<BrowserContext>.Channel => Channel;98 public IBrowser Browser { get; }99 public IReadOnlyList<IPage> Pages => PagesList;100 internal float DefaultNavigationTimeout101 {102 get => _defaultNavigationTimeout ?? PlaywrightImpl.DefaultTimeout;103 set104 {105 _defaultNavigationTimeout = value;106 Channel.SetDefaultNavigationTimeoutNoReplyAsync(value).IgnoreException();107 }108 }109 internal float DefaultTimeout110 {111 get => _defaultTimeout ?? PlaywrightImpl.DefaultTimeout;112 set113 {114 _defaultTimeout = value;115 Channel.SetDefaultTimeoutNoReplyAsync(value).IgnoreException();116 }117 }118 internal BrowserContextChannel Channel { get; }119 internal List<Page> PagesList { get; } = new();120 internal Page OwnerPage { get; set; }121 internal List<Worker> ServiceWorkersList { get; } = new();122 internal bool IsChromium => _initializer.IsChromium;123 internal BrowserNewContextOptions Options { get; set; }124 public Task AddCookiesAsync(IEnumerable<Cookie> cookies) => Channel.AddCookiesAsync(cookies);125 public Task AddInitScriptAsync(string script = null, string scriptPath = null)126 {127 if (string.IsNullOrEmpty(script))128 {129 script = ScriptsHelper.EvaluationScript(script, scriptPath);130 }131 return Channel.AddInitScriptAsync(script);132 }133 public Task ClearCookiesAsync() => Channel.ClearCookiesAsync();134 public Task ClearPermissionsAsync() => Channel.ClearPermissionsAsync();135 public async Task CloseAsync()136 {137 try138 {139 if (Options.RecordHarPath != null)140 {141 Artifact artifact = await Channel.HarExportAsync().ConfigureAwait(false);142 await artifact.SaveAsAsync(Options.RecordHarPath).ConfigureAwait(false);143 await artifact.DeleteAsync().ConfigureAwait(false);144 }145 await Channel.CloseAsync().ConfigureAwait(false);146 await _closeTcs.Task.ConfigureAwait(false);147 }148 catch (Exception e) when (DriverMessages.IsSafeCloseError(e))149 {150 // Swallow exception151 }152 }153 public Task<IReadOnlyList<BrowserContextCookiesResult>> CookiesAsync(IEnumerable<string> urls = null) => Channel.CookiesAsync(urls);154 public Task ExposeBindingAsync(string name, Action callback, BrowserContextExposeBindingOptions options = default)155 => ExposeBindingAsync(name, callback, handle: options?.Handle ?? false);156 public Task ExposeBindingAsync(string name, Action<BindingSource> callback)157 => ExposeBindingAsync(name, (Delegate)callback);158 public Task ExposeBindingAsync<T>(string name, Action<BindingSource, T> callback)159 => ExposeBindingAsync(name, (Delegate)callback);160 public Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, TResult> callback)161 => ExposeBindingAsync(name, (Delegate)callback);162 public Task ExposeBindingAsync<TResult>(string name, Func<BindingSource, IJSHandle, TResult> callback)163 => ExposeBindingAsync(name, callback, true);164 public Task ExposeBindingAsync<T, TResult>(string name, Func<BindingSource, T, TResult> callback)165 => ExposeBindingAsync(name, (Delegate)callback);166 public Task ExposeBindingAsync<T1, T2, TResult>(string name, Func<BindingSource, T1, T2, TResult> callback)167 => ExposeBindingAsync(name, (Delegate)callback);168 public Task ExposeBindingAsync<T1, T2, T3, TResult>(string name, Func<BindingSource, T1, T2, T3, TResult> callback)169 => ExposeBindingAsync(name, (Delegate)callback);170 public Task ExposeBindingAsync<T1, T2, T3, T4, TResult>(string name, Func<BindingSource, T1, T2, T3, T4, TResult> callback)171 => ExposeBindingAsync(name, (Delegate)callback);172 public Task ExposeFunctionAsync(string name, Action callback)173 => ExposeBindingAsync(name, (BindingSource _) => callback());174 public Task ExposeFunctionAsync<T>(string name, Action<T> callback)175 => ExposeBindingAsync(name, (BindingSource _, T t) => callback(t));176 public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> callback)177 => ExposeBindingAsync(name, (BindingSource _) => callback());178 public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> callback)179 => ExposeBindingAsync(name, (BindingSource _, T t) => callback(t));180 public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> callback)181 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2) => callback(t1, t2));182 public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> callback)183 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2, T3 t3) => callback(t1, t2, t3));184 public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> callback)185 => ExposeBindingAsync(name, (BindingSource _, T1 t1, T2 t2, T3 t3, T4 t4) => callback(t1, t2, t3, t4));186 public Task GrantPermissionsAsync(IEnumerable<string> permissions, BrowserContextGrantPermissionsOptions options = default)187 => Channel.GrantPermissionsAsync(permissions, options?.Origin);188 public async Task<IPage> NewPageAsync()189 {190 if (OwnerPage != null)191 {192 throw new PlaywrightException("Please use Browser.NewContextAsync()");193 }194 return (await Channel.NewPageAsync().ConfigureAwait(false)).Object;195 }196 public Task RouteAsync(string url, Action<IRoute> handler, BrowserContextRouteOptions options = default)197 => RouteAsync(new Regex(CombineUrlWithBase(url).GlobToRegex()), null, handler, options);198 public Task RouteAsync(Regex url, Action<IRoute> handler, BrowserContextRouteOptions options = default)199 => RouteAsync(url, null, handler, options);200 public Task RouteAsync(Func<string, bool> url, Action<IRoute> handler, BrowserContextRouteOptions options = default)201 => RouteAsync(null, url, handler, options);202 public Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)203 => Channel.SetExtraHTTPHeadersAsync(headers);204 public Task SetGeolocationAsync(Geolocation geolocation) => Channel.SetGeolocationAsync(geolocation);205 public Task SetOfflineAsync(bool offline) => Channel.SetOfflineAsync(offline);206 public async Task<string> StorageStateAsync(BrowserContextStorageStateOptions options = default)207 {208 string state = JsonSerializer.Serialize(209 await Channel.GetStorageStateAsync().ConfigureAwait(false),210 JsonExtensions.DefaultJsonSerializerOptions);211 if (!string.IsNullOrEmpty(options?.Path))212 {213 File.WriteAllText(options?.Path, state);214 }215 return state;216 }217 public Task UnrouteAsync(string urlString, Action<IRoute> handler = default)218 => UnrouteAsync(new Regex(CombineUrlWithBase(urlString).GlobToRegex()), null, handler);219 public Task UnrouteAsync(Regex urlRegex, Action<IRoute> handler = default)220 => UnrouteAsync(urlRegex, null, handler);221 public Task UnrouteAsync(Func<string, bool> urlFunc, Action<IRoute> handler = default)222 => UnrouteAsync(null, urlFunc, handler);223 public async Task<T> InnerWaitForEventAsync<T>(PlaywrightEvent<T> playwrightEvent, Func<Task> action = default, Func<T, bool> predicate = default, float? timeout = default)224 {225 if (playwrightEvent == null)226 {227 throw new ArgumentException("Page event is required", nameof(playwrightEvent));228 }229 timeout ??= DefaultTimeout;230 using var waiter = new Waiter(this, $"context.WaitForEventAsync(\"{playwrightEvent.Name}\")");231 waiter.RejectOnTimeout(Convert.ToInt32(timeout), $"Timeout {timeout}ms exceeded while waiting for event \"{playwrightEvent.Name}\"");232 if (playwrightEvent.Name != BrowserContextEvent.Close.Name)233 {234 waiter.RejectOnEvent<IBrowserContext>(this, BrowserContextEvent.Close.Name, new("Context closed"));235 }236 var result = waiter.WaitForEventAsync(this, playwrightEvent.Name, predicate);237 if (action != null)238 {239 await WrapApiBoundaryAsync(() => Task.WhenAll(result, action())).ConfigureAwait(false);240 }241 return await result.ConfigureAwait(false);242 }243 public Task<IPage> WaitForPageAsync(BrowserContextWaitForPageOptions options = default)244 => InnerWaitForEventAsync(BrowserContextEvent.Page, null, options?.Predicate, options?.Timeout);245 public Task<IPage> RunAndWaitForPageAsync(Func<Task> action, BrowserContextRunAndWaitForPageOptions options = default)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)...
RouteSetting.cs
Source:RouteSetting.cs
...24using System;25using System.Text.RegularExpressions;26namespace Microsoft.Playwright.Core27{28 internal class RouteSetting29 {30 public Regex Regex { get; set; }31 public Func<string, bool> Function { get; set; }32 public Action<IRoute> Handler { get; set; }33 public int? Times { get; internal set; }34 public int HandledCount { get; set; }35 public void Handle(IRoute route)36 {37 ++HandledCount;38 Handler(route);39 }40 public bool IsActive()41 {42 if (Times == null)...
RouteSetting
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync();3var context = await browser.NewContextAsync();4var page = await context.NewPageAsync();5await page.ClickAsync("text=About");6await page.ClickAsync("text=Contact");7await page.ClickAsync("text=Blog");8await page.ClickAsync("text=Careers");9await page.ClickAsync("text=Press");10await page.ClickAsync("text=Partners");11await page.ClickAsync("text=Terms");12await page.ClickAsync("text=Privacy");13await page.ClickAsync("text=Security");14await page.ClickAsync("text=Help");15await page.ClickAsync("text=Status");16await page.ClickAsync("text=Docs");17await page.ClickAsync("text=Contact GitHub");18await page.ClickAsync("text=Pricing");19await page.ClickAsync("text=API");20await page.ClickAsync("text=Training");21await page.ClickAsync("text=Blog");22await page.ClickAsync("text=About");23await page.ClickAsync("text=GitHub");24await page.ClickAsync("text=Contact GitHub");25await page.ClickAsync("text=Terms");26await page.ClickAsync("text=Privacy");27await page.ClickAsync("text=Security");28await page.ClickAsync("text=Status");29await page.ClickAsync("text=Help");30await page.ClickAsync("text=Docs");31await page.ClickAsync("text=GitHub");32await page.ClickAsync("text=GitHub");33await page.ClickAsync("text=Contact GitHub");34await page.ClickAsync("text=Pricing");35await page.ClickAsync("text=API");36await page.ClickAsync("text=Training");37await page.ClickAsync("text=Blog");38await page.ClickAsync("text=About");39await page.ClickAsync("text=GitHub");40await page.ClickAsync("text=Contact GitHub");41await page.ClickAsync("text=Terms");42await page.ClickAsync("text=Privacy");43await page.ClickAsync("text=Security");44await page.ClickAsync("text=Status");45await page.ClickAsync("text=Help");46await page.ClickAsync("text=Docs");47await page.ClickAsync("text=GitHub");48await page.ClickAsync("text=GitHub");49await page.ClickAsync("text=Contact GitHub");50await page.ClickAsync("text=Pricing");51await page.ClickAsync("text=API");52await page.ClickAsync("text=Training");53await page.ClickAsync("text=Blog");
RouteSetting
Using AI Code Generation
1using Microsoft.Playwright.Core;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });10 var context = await browser.NewContextAsync(new BrowserNewContextOptions11 {12 RecordHar = new HarOptions { Path = @"C:\Users\Public\Downloads\harfile.har" }13 });14 var page = await context.NewPageAsync();15 await context.CloseAsync();16 }17 }18}19using Microsoft.Playwright.Core;20using System;21using System.Threading.Tasks;22{23 {24 static async Task Main(string[] args)25 {26 await using var playwright = await Playwright.CreateAsync();27 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });28 var context = await browser.NewContextAsync(new BrowserNewContextOptions29 {30 RecordHar = new HarOptions { Path = @"C:\Users\Public\Downloads\harfile.har" }31 });32 var page = await context.NewPageAsync();33 await context.CloseAsync();34 }35 }36}37using Microsoft.Playwright.Core;38using System;39using System.Threading.Tasks;40{41 {42 static async Task Main(string[] args)43 {44 await using var playwright = await Playwright.CreateAsync();45 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });46 var context = await browser.NewContextAsync(new BrowserNewContextOptions47 {48 RecordHar = new HarOptions { Path = @"C:\Users\Public\Downloads\harfile.har" }49 });50 var page = await context.NewPageAsync();51 await context.CloseAsync();52 }53 }54}55using Microsoft.Playwright.Core;56using System;57using System.Threading.Tasks;58{59 {60 static async Task Main(string[]
RouteSetting
Using AI Code Generation
1using Microsoft.Playwright.Core;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync(new BrowserNewContextOptions13 {14 {15 }16 });17 var page = await context.NewPageAsync();18 await page.ScreenshotAsync(new PageScreenshotOptions19 {20 });21 await browser.CloseAsync();22 }23 }24}25var context = await browser.NewContextAsync(new BrowserNewContextOptions26 {27 {28 {29 }30 }31 });32Microsoft.Playwright.Core.PlaywrightException: 'VideoSize' does not contain a definition for 'Width' and no accessible extension method 'Width' accepting a first argument of type 'VideoSize' could be found (are you missing a using directive or an assembly reference?)
RouteSetting
Using AI Code Generation
1using Microsoft.Playwright.Core;2using Microsoft.Playwright.Transport;3using Microsoft.Playwright.Transport.Channels;4using Microsoft.Playwright.Transport.Protocol;5using System;6using System.Collections.Generic;7using System.Text;8using System.Threading.Tasks;9{10 {11 public string Url { get; set; }12 public string Method { get; set; }13 public int StatusCode { get; set; }14 public string Body { get; set; }15 public Dictionary<string, string> Headers { get; set; }16 }17}18using Microsoft.Playwright.Core;19using Microsoft.Playwright.Transport;20using Microsoft.Playwright.Transport.Channels;21using Microsoft.Playwright.Transport.Protocol;22using System;23using System.Collections.Generic;24using System.Text;25using System.Threading.Tasks;26{27 {28 public string Url { get; set; }29 public string Method { get; set; }30 public int StatusCode { get; set; }31 public string Body { get; set; }32 public Dictionary<string, string> Headers { get; set; }33 }34}35using Microsoft.Playwright.Core;36using Microsoft.Playwright.Transport;37using Microsoft.Playwright.Transport.Channels;38using Microsoft.Playwright.Transport.Protocol;39using System;40using System.Collections.Generic;41using System.Text;42using System.Threading.Tasks;43{44 {45 public string Url { get; set; }46 public string Method { get; set; }47 public int StatusCode { get; set; }48 public string Body { get; set; }49 public Dictionary<string, string> Headers { get; set; }50 }51}52using Microsoft.Playwright.Core;53using Microsoft.Playwright.Transport;54using Microsoft.Playwright.Transport.Channels;55using Microsoft.Playwright.Transport.Protocol;56using System;57using System.Collections.Generic;58using System.Text;59using System.Threading.Tasks;60{61 {62 public string Url { get; set; }63 public string Method { get; set; }64 public int StatusCode { get; set
RouteSetting
Using AI Code Generation
1{2 {3 public RouteSetting(string url, string method)4 {5 Url = new Regex(url);6 Method = method;7 }8 }9}10{11 {12 public Regex Url { get; set; }13 public string Method { get; set; }14 }15}16{17 {18 public Regex Url { get; set; }19 public string Method { get; set; }20 }21}22{23 {24 public Regex Url { get; set; }25 public string Method { get; set; }26 }27}28{29 {30 public Regex Url { get; set; }31 public string Method { get; set; }32 }33}34{35 {36 public Regex Url { get; set; }37 public string Method { get; set; }38 }39}40{41 {42 public Regex Url { get; set; }43 public string Method { get; set; }44 }45}46{47 {48 public Regex Url { get; set; }49 public string Method { get; set; }50 }51}52{53 {54 public Regex Url { get; set; }55 public string Method { get; set; }56 }57}58{59 {60 public Regex Url { get; set; }61 public string Method { get; set; }62 }63}64{65 {66 public Regex Url { get; set; }67 public string Method { get
RouteSetting
Using AI Code Generation
1var routeSetting = new RouteSetting();2routeSetting.Method = "GET";3routeSetting.Handler = async (route, request) =>4{5 await route.ContinueAsync();6};7await page.RouteAsync(routeSetting);8var routeSetting = new RouteSetting();9routeSetting.Method = "GET";10routeSetting.Handler = async (route, request) =>11{12 await route.ContinueAsync();13};14await page.RouteAsync(routeSetting);15var routeSetting = new RouteSetting();16routeSetting.Method = "GET";17routeSetting.Handler = async (route, request) =>18{19 await route.ContinueAsync();20};21await page.RouteAsync(routeSetting);22var routeSetting = new RouteSetting();23routeSetting.Method = "GET";24routeSetting.Handler = async (route, request) =>25{26 await route.ContinueAsync();27};28await page.RouteAsync(routeSetting);29var routeSetting = new RouteSetting();30routeSetting.Method = "GET";31routeSetting.Handler = async (route, request) =>32{33 await route.ContinueAsync();34};35await page.RouteAsync(routeSetting);36var routeSetting = new RouteSetting();37routeSetting.Method = "GET";38routeSetting.Handler = async (route, request) =>39{40 await route.ContinueAsync();41};42await page.RouteAsync(routeSetting);43var routeSetting = new RouteSetting();44routeSetting.Method = "GET";45routeSetting.Handler = async (route, request) =>46{47 await route.ContinueAsync();48};49await page.RouteAsync(routeSetting);50var routeSetting = new RouteSetting();
RouteSetting
Using AI Code Generation
1using Microsoft.Playwright.Core;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(headless: false);10 var context = await browser.NewContextAsync();11 var page = await context.NewPageAsync();12 await page.RouteAsync("**/*", route => route.ContinueAsync());13 }14 }15}16using Microsoft.Playwright;17using System;18using System.Threading.Tasks;19{20 {21 static async Task Main(string[] args)22 {23 using var playwright = await Playwright.CreateAsync();24 await using var browser = await playwright.Chromium.LaunchAsync(headless: false);25 var context = await browser.NewContextAsync();26 var page = await context.NewPageAsync();27 await page.RouteAsync("**/*", route => route.ContinueAsync());28 }29 }30}31using Microsoft.Playwright;32using System;33using System.Threading.Tasks;34{35 {36 static async Task Main(string[] args)37 {38 using var playwright = await Playwright.CreateAsync();39 await using var browser = await playwright.Chromium.LaunchAsync(headless: false);40 var context = await browser.NewContextAsync();41 var page = await context.NewPageAsync();42 await page.RouteAsync("**/*", route => route.ContinueAsync());43 }
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.
Get 100 minutes of automation test minutes FREE!!