Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.BindingCall.BindingCall
Page.cs
Source:Page.cs
...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;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 finally...
Connection.cs
Source:Connection.cs
...222 {223 case ChannelOwnerType.Artifact:224 result = new Artifact(parent, guid, initializer?.ToObject<ArtifactInitializer>(DefaultJsonSerializerOptions));225 break;226 case ChannelOwnerType.BindingCall:227 result = new BindingCall(parent, guid, initializer?.ToObject<BindingCallInitializer>(DefaultJsonSerializerOptions));228 break;229 case ChannelOwnerType.Playwright:230 result = new PlaywrightImpl(parent, guid, initializer?.ToObject<PlaywrightInitializer>(DefaultJsonSerializerOptions));231 break;232 case ChannelOwnerType.Browser:233 var browserInitializer = initializer?.ToObject<BrowserInitializer>(DefaultJsonSerializerOptions);234 result = new Browser(parent, guid, browserInitializer);235 break;236 case ChannelOwnerType.BrowserType:237 var browserTypeInitializer = initializer?.ToObject<BrowserTypeInitializer>(DefaultJsonSerializerOptions);238 result = new Core.BrowserType(parent, guid, browserTypeInitializer);239 break;240 case ChannelOwnerType.BrowserContext:241 var browserContextInitializer = initializer?.ToObject<BrowserContextInitializer>(DefaultJsonSerializerOptions);...
BrowserContext.cs
Source:BrowserContext.cs
...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)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 {...
PageChannel.cs
Source:PageChannel.cs
...41 internal event EventHandler Crashed;42 internal event EventHandler<IWebSocket> WebSocket;43 internal event EventHandler DOMContentLoaded;44 internal event EventHandler<PageChannelPopupEventArgs> Popup;45 internal event EventHandler<BindingCallEventArgs> BindingCall;46 internal event EventHandler<RouteEventArgs> Route;47 internal event EventHandler<IFrame> FrameAttached;48 internal event EventHandler<IFrame> FrameDetached;49 internal event EventHandler<IDialog> Dialog;50 internal event EventHandler<IConsoleMessage> Console;51 internal event EventHandler<PageDownloadEvent> Download;52 internal event EventHandler<SerializedError> PageError;53 internal event EventHandler<FileChooserChannelEventArgs> FileChooser;54 internal event EventHandler Load;55 internal event EventHandler<WorkerChannelEventArgs> Worker;56 internal event EventHandler<VideoEventArgs> Video;57 internal override void OnMessage(string method, JsonElement? serverParams)58 {59 switch (method)60 {61 case "close":62 Closed?.Invoke(this, EventArgs.Empty);63 break;64 case "crash":65 Crashed?.Invoke(this, EventArgs.Empty);66 break;67 case "domcontentloaded":68 DOMContentLoaded?.Invoke(this, EventArgs.Empty);69 break;70 case "load":71 Load?.Invoke(this, EventArgs.Empty);72 break;73 case "bindingCall":74 BindingCall?.Invoke(75 this,76 new() { BindingCall = serverParams?.GetProperty("binding").ToObject<BindingCallChannel>(Connection.DefaultJsonSerializerOptions).Object });77 break;78 case "route":79 var route = serverParams?.GetProperty("route").ToObject<RouteChannel>(Connection.DefaultJsonSerializerOptions).Object;80 var request = serverParams?.GetProperty("request").ToObject<RequestChannel>(Connection.DefaultJsonSerializerOptions).Object;81 Route?.Invoke(82 this,83 new() { Route = route, Request = request });84 break;85 case "popup":86 Popup?.Invoke(this, new() { Page = serverParams?.GetProperty("page").ToObject<PageChannel>(Connection.DefaultJsonSerializerOptions).Object });87 break;88 case "pageError":89 PageError?.Invoke(this, serverParams?.GetProperty("error").GetProperty("error").ToObject<SerializedError>(Connection.DefaultJsonSerializerOptions));90 break;...
BrowserContextChannel.cs
Source:BrowserContextChannel.cs
...39 internal event EventHandler Close;40 internal event EventHandler<BrowserContextPageEventArgs> Page;41 internal event EventHandler<BrowserContextPageEventArgs> BackgroundPage;42 internal event EventHandler<WorkerChannelEventArgs> ServiceWorker;43 internal event EventHandler<BindingCallEventArgs> BindingCall;44 internal event EventHandler<RouteEventArgs> Route;45 internal event EventHandler<BrowserContextChannelRequestEventArgs> Request;46 internal event EventHandler<BrowserContextChannelRequestEventArgs> RequestFinished;47 internal event EventHandler<BrowserContextChannelRequestEventArgs> RequestFailed;48 internal event EventHandler<BrowserContextChannelResponseEventArgs> Response;49 internal override void OnMessage(string method, JsonElement? serverParams)50 {51 switch (method)52 {53 case "close":54 Close?.Invoke(this, EventArgs.Empty);55 break;56 case "bindingCall":57 BindingCall?.Invoke(58 this,59 new() { BindingCall = serverParams?.GetProperty("binding").ToObject<BindingCallChannel>(Connection.DefaultJsonSerializerOptions).Object });60 break;61 case "route":62 var route = serverParams?.GetProperty("route").ToObject<RouteChannel>(Connection.DefaultJsonSerializerOptions).Object;63 var request = serverParams?.GetProperty("request").ToObject<RequestChannel>(Connection.DefaultJsonSerializerOptions).Object;64 Route?.Invoke(65 this,66 new() { Route = route, Request = request });67 break;68 case "page":69 Page?.Invoke(70 this,71 new() { PageChannel = serverParams?.GetProperty("page").ToObject<PageChannel>(Connection.DefaultJsonSerializerOptions) });72 break;73 case "crBackgroundPage":...
BindingCall.cs
Source:BindingCall.cs
...30using Microsoft.Playwright.Transport.Channels;31using Microsoft.Playwright.Transport.Protocol;32namespace Microsoft.Playwright.Core33{34 internal class BindingCall : ChannelOwnerBase, IChannelOwner<BindingCall>35 {36 private static readonly Type VoidTaskResultType = Type.GetType("System.Threading.Tasks.VoidTaskResult");37 private readonly BindingCallChannel _channel;38 private readonly BindingCallInitializer _initializer;39 public BindingCall(IChannelOwner parent, string guid, BindingCallInitializer initializer) : base(parent, guid)40 {41 _channel = new(guid, parent.Connection, this);42 _initializer = initializer;43 }44 public string Name => _initializer.Name;45 ChannelBase IChannelOwner.Channel => _channel;46 IChannel<BindingCall> IChannelOwner<BindingCall>.Channel => _channel;47 internal async Task CallAsync(Delegate binding)48 {49 try50 {51 const string taskResultPropertyName = "Result";52 var methodParams = binding.Method.GetParameters().Select(parameter => parameter.ParameterType).Skip(1).ToArray();53 var args = new List<object>54 {55 new BindingSource56 {57 Context = _initializer?.Frame?.Page?.Context,58 Page = _initializer?.Frame?.Page,59 Frame = _initializer?.Frame,60 },...
BindingCallChannelImpl.cs
Source:BindingCallChannelImpl.cs
...35using Microsoft.Playwright.Helpers;36#nullable enable37namespace Microsoft.Playwright.Transport.Channels38{39 internal class BindingCallChannelImpl : Channel<BindingCall>40 {41 public BindingCallChannelImpl(string guid, Connection connection, BindingCall owner) : base(guid, connection, owner)42 {43 }44 internal virtual async Task RejectAsync(Exception error)45 => await Connection.SendMessageToServerAsync<JsonElement>(46 Guid,47 "reject",48 new49 {50 error = error.ToObject(),51 }52 )53 .ConfigureAwait(false);54 internal virtual async Task ResolveAsync(object result)55 => await Connection.SendMessageToServerAsync<JsonElement>(56 Guid,57 "resolve",58 new59 {60 result = result,61 }62 )63 .ConfigureAwait(false);64 }65 internal partial class BindingCallChannel : BindingCallChannelImpl66 {67 public BindingCallChannel(string guid, Connection connection, BindingCall owner) : base(guid, connection, owner)68 {69 }70 }71}72#nullable disable...
BindingCallEventArgs.cs
Source:BindingCallEventArgs.cs
...24using System;25using Microsoft.Playwright.Core;26namespace Microsoft.Playwright.Transport.Channels27{28 internal class BindingCallEventArgs : EventArgs29 {30 public BindingCall BindingCall { get; set; }31 }32}...
BindingCall
Using AI Code Generation
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 page = await browser.NewPageAsync();13 await page.ExposeBindingAsync("myBinding", (BindingCall bindingCall) =>14 {15 Console.WriteLine(bindingCall);16 return Task.CompletedTask;17 });18 await page.EvaluateAsync("() => { window.myBinding('hello', 'world'); }");19 }20 }21}22using System;23using System.Threading.Tasks;24using Microsoft.Playwright;25{26 {27 static async Task Main(string[] args)28 {29 using var playwright = await Playwright.CreateAsync();30 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions31 {32 });33 var page = await browser.NewPageAsync();34 await page.ExposeBindingAsync("myBinding", (BindingCall bindingCall) =>35 {36 Console.WriteLine(bindingCall);37 return Task.CompletedTask;38 });39 await page.EvaluateAsync("() => { window.myBinding('hello', 'world'); }");40 }41 }42}
BindingCall
Using AI Code Generation
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 page = await browser.NewPageAsync();13 await page.ExposeBindingAsync("test", (BindingCall bindingCall) =>14 {15 Console.WriteLine(bindingCall.Arguments[0].ToString());16 return Task.CompletedTask;
BindingCall
Using AI Code Generation
1var browser = await Playwright.CreateAsync();2var context = await browser.NewContextAsync();3var page = await context.NewPageAsync();4await page.EvaluateAsync(@"() => {5 window['someFunction'] = (e) => {6 console.log('someFunction called with: ' + e);7 }8 window['someFunction']('Hello World');9}");10await browser.CloseAsync();11var browser = await Playwright.CreateAsync();12var context = await browser.NewContextAsync();13var page = await context.NewPageAsync();14await page.EvaluateAsync(@"() => {15 window['someFunction'] = (e) => {16 console.log('someFunction called with: ' + e);17 }18 window['someFunction']('Hello World');19}");20await browser.CloseAsync();21var browser = await Playwright.CreateAsync();22var context = await browser.NewContextAsync();23var page = await context.NewPageAsync();24await page.EvaluateAsync(@"() => {25 window['someFunction'] = (e) => {26 console.log('someFunction called with: ' + e);27 }28 window['someFunction']('Hello World');29}");30await browser.CloseAsync();31var browser = await Playwright.CreateAsync();32var context = await browser.NewContextAsync();33var page = await context.NewPageAsync();34await page.EvaluateAsync(@"() => {35 window['someFunction'] = (e) => {36 console.log('someFunction called with: ' + e);37 }38 window['someFunction']('Hello World');39}");40await browser.CloseAsync();41var browser = await Playwright.CreateAsync();42var context = await browser.NewContextAsync();43var page = await context.NewPageAsync();44await page.EvaluateAsync(@"() =>
BindingCall
Using AI Code Generation
1PlaywrightSharp.BrowserType.LaunchAsync(LaunchOptions options = null)2Microsoft.Playwright.BrowserType.LaunchAsync(Microsoft.Playwright.LaunchOptions options = null)3PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)4Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)5PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)6Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)7PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)8Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)9PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)10Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)11PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)12Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)13PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)14Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)15PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)16Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)17PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)18Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)19PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)20Microsoft.Playwright.BrowserType.LaunchPersistentContextAsync(string userDataDir, Microsoft.Playwright.LaunchOptions options = null)21PlaywrightSharp.BrowserType.LaunchPersistentContextAsync(string userDataDir, LaunchOptions options = null)
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!!