How to use BrowserContext class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.BrowserContext

PuppeteerBrowserBuilder.cs

Source:PuppeteerBrowserBuilder.cs Github

copy

Full Screen

...188 Args = _browserProperties.ToArray()189 };190 var browser = await Puppeteer.LaunchAsync(launchOptions);191 var context = _isIncognito192 ? await browser.CreateIncognitoBrowserContextAsync()193 : browser.DefaultContext;194 return new ChromiumBrowser(_browserConfig, _delayService, _loggingContext, this, browser, context, _overridePermissions);195 }196 }197 private class ChromiumBrowser : IPuppeteerBrowser198 {199 private static readonly Regex RegexStripHtmlTags = new Regex("<.*?>");200 private readonly ILogger _logger;201 private readonly IBrowserViewPortConfig _browserConfig;202 private readonly IDelayService _delayService;203 private readonly Browser _browser;204 private readonly BrowserContext _browserContext;205 private readonly IPuppeteerContext _puppeteerContext;206 private readonly IEnumerable<OverridePermission> _overridePermissions;207 private readonly AsyncRetryPolicy _policyNoData;208 private readonly decimal[] _diagonalClickDevisors = new decimal[] {5, 4, 3, 2, 1.6M, 1.4M, 1.2M, 1.1M};209 public ChromiumBrowser(IBrowserViewPortConfig browserConfig, IDelayService delayService, ILoggingContext loggingContext, IPuppeteerContext puppeteerContext, 210 Browser browser, BrowserContext browserContext, IEnumerable<OverridePermission> overridePermissions)211 {212 _logger = loggingContext.CreateLogger<IPuppeteerBrowser>();213 _browserConfig = browserConfig;214 _delayService = delayService;215 _puppeteerContext = puppeteerContext;216 _browser = browser;217 _browserContext = browserContext;218 _overridePermissions = overridePermissions;219 if (puppeteerContext.BrowserEvents)220 {221 _browser.Closed += _browser_Closed;222 _browser.Disconnected += _browser_Disconnected;223 _browser.TargetChanged += _browser_TargetChanged;224 _browser.TargetCreated += _browser_TargetCreated;225 _browser.TargetDestroyed += _browser_TargetDestroyed;226 }227 _policyNoData = Policy228 .Handle<TimeoutException>().RetryAsync(_diagonalClickDevisors.Length,229 (exception, retryN, context) =>230 {231 _logger.Warn($"Diagonal Clicks Try#{retryN}");232 });233 }234 private void _browser_TargetDestroyed(object sender, TargetChangedArgs e)235 {236 _logger.Warn($"Browser: Target has been destroyed");237 }238 private void _browser_TargetCreated(object sender, TargetChangedArgs e)239 {240 _logger.Warn($"Browser: Target has been created");241 }242 private void _browser_TargetChanged(object sender, TargetChangedArgs e)243 {244 _logger.Warn($"Browser: Target has been changed");245 }246 private void _browser_Disconnected(object sender, EventArgs e)247 {248 _logger.Warn("Browser has been disconnected");249 }250 private void _browser_Closed(object sender, EventArgs e)251 {252 _logger.Warn("Browser has been closed");253 }254 /// <summary>255 /// Setup the chromium for browser automation256 /// </summary>257 /// <returns></returns>258 async Task IPuppeteerBrowser.ClickAsync(Page page, string clickPlace, ClickOptions clickOptions)259 {260 await page.ClickAsync(clickPlace, clickOptions);261 } 262 async Task<string> IPuppeteerBrowser.GetContentAsync(Page page)263 {264 return await page.GetContentAsync();265 }266 async Task<Page> IPuppeteerBrowser.WaitGetPage(Page page, string selector, string targetId)267 { 268 var newTarget = await _browserContext.WaitForTargetAsync(a => a.Opener?.TargetId == targetId, new WaitForOptions { Timeout = 10 * 1000 });269 var newPage = await newTarget.PageAsync();270 await SetPageOptions(newPage);271 await newPage.WaitForSelectorAsync(selector);272 return newPage;273 }274 async Task IPuppeteerBrowser.CloseAsync()275 {276 await _browser.CloseAsync();277 }278 async Task<Page> IPuppeteerBrowser.ClickAndGetPage(ElementHandle element, string targetId)279 {280 await element.ClickAsync();281 var newTarget = await _browserContext.WaitForTargetAsync(a => a.Opener?.TargetId == targetId);282 var newPage = await newTarget.PageAsync();283 await SetPageOptions(newPage);284 return newPage;285 }286 async Task<Page> IPuppeteerBrowser.MouseClickAndGetPage(BoundingBox box, Page page)287 {288 int retryN = 0;289 return await _policyNoData.ExecuteAsync(async () =>290 {291 var pages = await _browserContext.PagesAsync();292 var pageCount = pages.Length;293 var listId = new List<string>();294 foreach (var page1 in pages)295 {296 var id = page1.Target?.TargetId;297 listId.Add(id);298 }299 await page.Keyboard.DownAsync("Control");300 await page.Mouse.ClickAsync(box.X + (box.Width / _diagonalClickDevisors[retryN]), box.Y + (box.Height / _diagonalClickDevisors[retryN]));301 await page.Keyboard.UpAsync("Control");302 var pages1 = await _browserContext.PagesAsync();303 if (pages1.Length <= pageCount)304 {305 retryN++;306 throw new TimeoutException();307 }308 var newPage = pages1.FirstOrDefault(a => !listId.Contains(a.Target?.TargetId));309 if (newPage == null)310 {311 throw new InvalidOperationException("Page not found after click");312 }313 if (_puppeteerContext.DialogHandler != null)314 {315 newPage.Dialog += _puppeteerContext.DialogHandler;316 }317 await SetPageOptions(newPage);318 return newPage;319 });320 }321 async Task<Page> IPuppeteerBrowser.ClickAndGetPage(ElementHandle element, string targetId, WaitForOptions waitForOptions)322 {323 await element.ClickAsync();324 var newTarget = await _browserContext.WaitForTargetAsync(a => a.Opener?.TargetId == targetId, waitForOptions);325 var newPage = await newTarget.PageAsync();326 await SetPageOptions(newPage);327 return newPage;328 }329 async Task<string> IPuppeteerBrowser.ClickButtonForContinue(Page page, string buttonXPath, string adUrl, params WaitUntilNavigation[] waitUntilNavigations)330 {331 var continueButtons = page.XPathAsync(buttonXPath);332 _logger.Info($"Needed click on button for continue. Url: {adUrl}");333 foreach (var continueButton in await continueButtons)334 {335 _logger.Debug($"Will click on {buttonXPath}");336 await continueButton.ClickAsync();337 var navigationTask = page.WaitForNavigationAsync(new NavigationOptions338 {339 WaitUntil = waitUntilNavigations340 });341 if (await Task.WhenAny(navigationTask, _delayService.DelayAsync(TimeSpan.FromSeconds(30))) == navigationTask)342 {343 _logger.Info($"Returned new url:'{page.Url}'");344 if (!page.Url.Contains("redirect/verify"))345 {346 return page.Url;347 }348 }349 return string.Empty;350 }351 return string.Empty;352 }353 async Task<Page[]> IPuppeteerBrowser.GetPages()354 {355 return await _browserContext.PagesAsync();356 }357 async Task<string> IPuppeteerBrowser.GetFramePage(string iframeSrc)358 {359 using (var multiVideopage = await _browserContext.NewPageAsync())360 {361 await SetPageOptions(multiVideopage);362 await multiVideopage.GoToAsync(iframeSrc, Convert.ToInt32(_puppeteerContext.PageLoadTimeout.TotalMilliseconds), new WaitUntilNavigation[] { WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load, WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2 });363 var data = await multiVideopage.GetContentAsync();364 return data;365 }366 }367 async Task<string> IPuppeteerBrowser.GetFramePage(Page page, string frameName)368 {369 var googlAdsFrame1 = page.Frames.ToList().FirstOrDefault(x => x.Name == frameName);370 if (googlAdsFrame1 == null)371 {372 return null;373 }374 return await googlAdsFrame1.GetContentAsync();375 }376 377 async Task<string> IPuppeteerBrowser.GetVideoAdsOnUrl(Page page, string xPath)378 {379 var elementToclick = await page.WaitForXPathAsync(xPath);380 if (elementToclick != null) 381 {382 await elementToclick.ClickAsync();383 return await page.EvaluateFunctionAsync<string>("() => navigator.clipboard.readText()");384 }385 _logger.Debug("GetVideoAdsOnUrl: elementToclick is null");386 return null;387 }388 /// <summary>389 /// Returns IpDetails by the specified url390 /// </summary>391 /// <param name="ipFetcherUrl">The ip details provider url.</param>392 /// <returns>The instance of <see cref="IpDetails"></see></returns>393 async Task<IpDetails> IPuppeteerBrowser.GetIpDetails(string ipFetcherUrl)394 {395 IpDetails ipDetails = await GetIpDetailsInternal(ipFetcherUrl);396 return ipDetails ?? new IpDetails397 {398 City = "N/A",399 ContinentName = "N/A",400 CountryCode = "N/A",401 CountryName = "N/A",402 IpAddress = "127.0.0.1",403 State = "N/A",404 ContinentCode = "N/A"405 };406 }407 /// <summary>408 /// Returns IpDetails by the specified url and, in case of error, returns the default country code and country name409 /// </summary>410 /// <param name="ipFetcherUrl">The ip details provider url.</param>411 /// <param name="defaultCountryCode">The country code tu return default details.</param>412 /// <returns>The instance of <see cref="IpDetails"></see></returns>413 async Task<IpDetails> IPuppeteerBrowser.GetIpDetails(string ipFetcherUrl, string defaultCountryCode)414 {415 IpDetails ipDetails = await GetIpDetailsInternal(ipFetcherUrl);416 return ipDetails ?? new IpDetails417 {418 City = "N/A",419 ContinentName = "N/A",420 CountryCode = defaultCountryCode,421 CountryName = References.Countries[defaultCountryCode],422 IpAddress = "127.0.0.1",423 State = "N/A",424 ContinentCode = "N/A"425 };426 }427 async Task<string> IPuppeteerBrowser.GetPageContent(string stringUrl, params WaitUntilNavigation[] waitUntilNavigations)428 {429 return await GetPageContentInternalAsync(stringUrl, waitUntilNavigations);430 }431 private async Task SetPageOptions(Page page)432 {433 var viewPortOptions = new ViewPortOptions434 { Width = _browserConfig.WindowWidth, Height = _browserConfig.WindowHeight };435 await page.SetViewportAsync(viewPortOptions);436 if (!string.IsNullOrWhiteSpace(_puppeteerContext.ProxyUserName))437 {438 await page.AuthenticateAsync(new Credentials439 {440 Username = _puppeteerContext.ProxyUserName,441 Password = _puppeteerContext.ProxyPwd442 });443 }444 }445 async Task<Page> IPuppeteerBrowser.GetPage(string url, TimeSpan? timeoutPageLoad, params WaitUntilNavigation[] waitUntilNavigations)446 {447 var page = await GoToPageAsync(url, timeoutPageLoad, waitUntilNavigations);448 if (_overridePermissions?.Any() ?? false)449 {450 await page.BrowserContext.OverridePermissionsAsync(page.Url,451 new []452 {453 OverridePermission.ClipboardWrite, OverridePermission.ClipboardRead,454 OverridePermission.AccessibilityEvents, OverridePermission.BackgroundSync,455 OverridePermission.Geolocation, OverridePermission.Microphone, OverridePermission.Notifications,456 OverridePermission.PaymentHandler/*, OverridePermission.Push*/457 });458 }459 return page;460 }461 async Task<string> IPuppeteerBrowser.GetScrolledPage(string url, int maxScroll, params WaitUntilNavigation[] waitUntilNavigations)462 {463 var pageResult = string.Empty;464 try...

Full Screen

Full Screen

Browser.cs

Source:Browser.cs Github

copy

Full Screen

...57 IgnoreHTTPSErrors = ignoreHTTPSErrors;58 DefaultViewport = defaultViewport;59 TargetsMap = new Dictionary<string, Target>();60 ScreenshotTaskQueue = new TaskQueue();61 DefaultContext = new BrowserContext(Connection, this, null);62 _contexts = contextIds.ToDictionary(keySelector: contextId => contextId,63 elementSelector: contextId => new BrowserContext(Connection, this, contextId));64 Connection.Closed += (object sender, EventArgs e) => Disconnected?.Invoke(this, new EventArgs());65 Connection.MessageReceived += Connect_MessageReceived;66 _chromiumProcess = chromiumProcess;67 _logger = Connection.LoggerFactory.CreateLogger<Browser>();68 }69 #region Private members70 internal readonly Dictionary<string, Target> TargetsMap;71 private readonly Dictionary<string, BrowserContext> _contexts;72 private readonly ILogger<Browser> _logger;73 private readonly ChromiumProcess _chromiumProcess;74 private Task _closeTask;75 #endregion76 #region Properties77 /// <summary>78 /// 79 /// </summary>80 public event EventHandler Closed;81 /// <summary>82 /// Raised when puppeteer gets disconnected from the Chromium instance. This might happen because one of the following83 /// - Chromium is closed or crashed84 /// - <see cref="Disconnect"/> method was called85 /// </summary>86 public event EventHandler Disconnected;87 /// <summary>88 /// Raised when the url of a target changes89 /// </summary>90 public event EventHandler<TargetChangedArgs> TargetChanged;91 /// <summary>92 /// Raised when a target is created, for example when a new page is opened by <c>window.open</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/Window/open"/> or <see cref="NewPageAsync"/>.93 /// </summary>94 public event EventHandler<TargetChangedArgs> TargetCreated;95 /// <summary>96 /// Raised when a target is destroyed, for example when a page is closed97 /// </summary>98 public event EventHandler<TargetChangedArgs> TargetDestroyed;99 /// <summary>100 /// Gets the Browser websocket url101 /// </summary>102 /// <remarks>103 /// Browser websocket endpoint which can be used as an argument to <see cref="Puppeteer.ConnectAsync(ConnectOptions, ILoggerFactory)"/>.104 /// The format is <c>ws://${host}:${port}/devtools/browser/[id]</c>105 /// You can find the <c>webSocketDebuggerUrl</c> from <c>http://${host}:${port}/json/version</c>.106 /// Learn more about the devtools protocol <see href="https://chromedevtools.github.io/devtools-protocol"/> 107 /// and the browser endpoint <see href="https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target"/>108 /// </remarks>109 public string WebSocketEndpoint => Connection.Url;110 /// <summary>111 /// Gets the spawned browser process. Returns <c>null</c> if the browser instance was created with <see cref="Puppeteer.ConnectAsync(ConnectOptions, ILoggerFactory)"/> method.112 /// </summary>113 public Process Process => _chromiumProcess?.Process;114 /// <summary>115 /// Gets or Sets whether to ignore HTTPS errors during navigation116 /// </summary>117 public bool IgnoreHTTPSErrors { get; set; }118 /// <summary>119 /// Gets a value indicating if the browser is closed120 /// </summary>121 public bool IsClosed => _closeTask != null && _closeTask.IsCompleted && _closeTask.Exception != null;122 /// <summary>123 /// Returns the default browser context. The default browser context can not be closed.124 /// </summary>125 /// <value>The default context.</value>126 public BrowserContext DefaultContext { get; }127 internal TaskQueue ScreenshotTaskQueue { get; set; }128 internal Connection Connection { get; }129 internal ViewPortOptions DefaultViewport { get; }130 #endregion131 #region Public Methods132 /// <summary>133 /// Creates a new page134 /// </summary>135 /// <returns>Task which resolves to a new <see cref="Page"/> object</returns>136 public Task<Page> NewPageAsync() => DefaultContext.NewPageAsync();137 /// <summary>138 /// Returns An Array of all active targets139 /// </summary>140 /// <returns>An Array of all active targets</returns>141 public Target[] Targets() => TargetsMap.Values.Where(target => target.IsInitialized).ToArray();142 /// <summary>143 /// A target associated with the browser.144 /// </summary>145 public Target Target => Targets().FirstOrDefault(t => t.Type == TargetType.Browser);146 /// <summary>147 /// Creates a new incognito browser context. This won't share cookies/cache with other browser contexts.148 /// </summary>149 /// <returns>Task which resolves to a new <see cref="BrowserContext"/> object</returns>150 /// <example>151 /// <code>152 /// <![CDATA[153 /// using(var browser = await Puppeteer.LaunchAsync(new LaunchOptions()))154 /// {155 /// // Create a new incognito browser context.156 /// var context = await browser.CreateIncognitoBrowserContextAsync();157 /// // Create a new page in a pristine context.158 /// var page = await context.NewPageAsync();159 /// // Do stuff160 /// await page.GoToAsync("https://example.com");161 /// }162 /// ]]>163 /// </code>164 /// </example>165 public async Task<BrowserContext> CreateIncognitoBrowserContextAsync()166 {167 var response = await Connection.SendAsync<CreateBrowserContextResponse>("Target.createBrowserContext", new { }).ConfigureAwait(false);168 var context = new BrowserContext(Connection, this, response.BrowserContextId);169 _contexts[response.BrowserContextId] = context;170 return context;171 }172 /// <summary>173 /// Returns an array of all open <see cref="BrowserContext"/>. In a newly created browser, this will return a single instance of <see cref="BrowserContext"/>174 /// </summary>175 /// <returns>An array of <see cref="BrowserContext"/> objects</returns>176 public BrowserContext[] BrowserContexts()177 {178 var allContexts = new BrowserContext[_contexts.Count + 1];179 allContexts[0] = DefaultContext;180 _contexts.Values.CopyTo(allContexts, 1);181 return allContexts;182 }183 /// <summary>184 /// Returns a Task which resolves to an array of all open pages.185 /// Non visible pages, such as <c>"background_page"</c>, will not be listed here. You can find them using <see cref="Target.PageAsync"/>186 /// </summary>187 /// <returns>Task which resolves to an array of all open pages inside the Browser. 188 /// In case of multiple browser contexts, the method will return an array with all the pages in all browser contexts.189 /// </returns>190 public async Task<Page[]> PagesAsync()191 => (await Task.WhenAll(192 BrowserContexts().Select(t => t.PagesAsync())).ConfigureAwait(false)193 ).SelectMany(p => p).ToArray();194 /// <summary>195 /// Gets the browser's version196 /// </summary>197 /// <returns>For headless Chromium, this is similar to <c>HeadlessChrome/61.0.3153.0</c>. For non-headless, this is similar to <c>Chrome/61.0.3153.0</c></returns>198 /// <remarks>199 /// the format of <see cref="GetVersionAsync"/> might change with future releases of Chromium200 /// </remarks>201 public async Task<string> GetVersionAsync()202 {203 var version = await Connection.SendAsync("Browser.getVersion").ConfigureAwait(false);204 return version[MessageKeys.Product].AsString();205 }206 /// <summary>207 /// Gets the browser's original user agent208 /// </summary>209 /// <returns>Task which resolves to the browser's original user agent</returns>210 /// <remarks>211 /// Pages can override browser user agent with <see cref="Page.SetUserAgentAsync(string)"/>212 /// </remarks>213 public async Task<string> GetUserAgentAsync()214 {215 var version = await Connection.SendAsync("Browser.getVersion").ConfigureAwait(false);216 return version[MessageKeys.UserAgent].AsString();217 }218 /// <summary>219 /// Disconnects Puppeteer from the browser, but leaves the Chromium process running. After calling <see cref="Disconnect"/>, the browser object is considered disposed and cannot be used anymore220 /// </summary>221 public void Disconnect() => Connection.Dispose();222 /// <summary>223 /// Closes Chromium and all of its pages (if any were opened). The browser object itself is considered disposed and cannot be used anymore224 /// </summary>225 /// <returns>Task</returns>226 public Task CloseAsync() => _closeTask ?? (_closeTask = CloseCoreAsync());227 private async Task CloseCoreAsync()228 {229 try230 {231 try232 {233 // Initiate graceful browser close operation but don't await it just yet,234 // because we want to ensure chromium process shutdown first.235 var browserCloseTask = Connection.SendAsync("Browser.close", null);236 if (_chromiumProcess != null)237 {238 // Notify chromium process that exit is expected, but should be enforced if it239 // doesn't occur withing the close timeout.240 var closeTimeout = TimeSpan.FromMilliseconds(CloseTimeout);241 await _chromiumProcess.EnsureExitAsync(closeTimeout).ConfigureAwait(false);242 }243 // Now we can safely await the browser close operation without risking keeping chromium244 // process running for indeterminate period.245 await browserCloseTask.ConfigureAwait(false);246 }247 finally248 {249 Disconnect();250 }251 }252 catch (Exception ex)253 {254 _logger.LogError(ex, ex.Message);255 if (_chromiumProcess != null)256 {257 await _chromiumProcess.KillAsync().ConfigureAwait(false);258 }259 }260 Closed?.Invoke(this, new EventArgs());261 }262 #endregion263 #region Private Methods264 internal void ChangeTarget(Target target)265 {266 var args = new TargetChangedArgs { Target = target };267 TargetChanged?.Invoke(this, args);268 target.BrowserContext.OnTargetChanged(this, args);269 }270 internal async Task<Page> CreatePageInContextAsync(string contextId)271 {272 var args = new Dictionary<string, object> { [MessageKeys.Url] = "about:blank" };273 if (contextId != null)274 {275 args[MessageKeys.BrowserContextId] = contextId;276 }277 var targetId = (await Connection.SendAsync("Target.createTarget", args).ConfigureAwait(false))[MessageKeys.TargetId].ToString();278 var target = TargetsMap[targetId];279 await target.InitializedTask.ConfigureAwait(false);280 return await target.PageAsync().ConfigureAwait(false);281 }282 internal async Task DisposeContextAsync(string contextId)283 {284 await Connection.SendAsync("Target.disposeBrowserContext", new { browserContextId = contextId }).ConfigureAwait(false);285 _contexts.Remove(contextId);286 }287 private async void Connect_MessageReceived(object sender, MessageEventArgs e)288 {289 switch (e.MessageID)290 {291 case "Target.targetCreated":292 await CreateTargetAsync(e.MessageData.ToObject<TargetCreatedResponse>()).ConfigureAwait(false);293 return;294 case "Target.targetDestroyed":295 await DestroyTargetAsync(e.MessageData.ToObject<TargetDestroyedResponse>()).ConfigureAwait(false);296 return;297 case "Target.targetInfoChanged":298 ChangeTargetInfo(e.MessageData.ToObject<TargetCreatedResponse>());299 return;300 }301 }302 private void ChangeTargetInfo(TargetCreatedResponse e)303 {304 if (!TargetsMap.ContainsKey(e.TargetInfo.TargetId))305 {306 throw new InvalidTargetException("Target should exists before ChangeTargetInfo");307 }308 var target = TargetsMap[e.TargetInfo.TargetId];309 target.TargetInfoChanged(e.TargetInfo);310 }311 private async Task DestroyTargetAsync(TargetDestroyedResponse e)312 {313 if (!TargetsMap.ContainsKey(e.TargetId))314 {315 throw new InvalidTargetException("Target should exists before DestroyTarget");316 }317 var target = TargetsMap[e.TargetId];318 TargetsMap.Remove(e.TargetId);319 target.CloseTaskWrapper.TrySetResult(true);320 if (await target.InitializedTask.ConfigureAwait(false))321 {322 var args = new TargetChangedArgs { Target = target };323 TargetDestroyed?.Invoke(this, args);324 target.BrowserContext.OnTargetDestroyed(this, args);325 }326 }327 private async Task CreateTargetAsync(TargetCreatedResponse e)328 {329 var targetInfo = e.TargetInfo;330 var browserContextId = targetInfo.BrowserContextId;331 if (!(browserContextId != null && _contexts.TryGetValue(browserContextId, out var context)))332 {333 context = DefaultContext;334 }335 var target = new Target(336 e.TargetInfo,337 info => Connection.CreateSessionAsync(info),338 context);339 if (TargetsMap.ContainsKey(e.TargetInfo.TargetId))340 {341 _logger.LogError("Target should not exist before targetCreated");342 }343 TargetsMap[e.TargetInfo.TargetId] = target;344 if (await target.InitializedTask.ConfigureAwait(false))...

Full Screen

Full Screen

UCFullPageScreenShot.cs

Source:UCFullPageScreenShot.cs Github

copy

Full Screen

...142 IgnoreHTTPSErrors = true,143 };144 using (var browser = await Puppeteer.LaunchAsync(option))145 {146 BrowserContext browserContext = browser.DefaultContext;147 //if (saveHis)148 //{149 // browserContext = await browser.CreateIncognitoBrowserContextAsync();150 //}151 var page = await browserContext.NewPageAsync();152 await page.SetUserAgentAsync(_userAgent);153 await page.SetViewportAsync(new ViewPortOptions154 {155 Width = Screen.PrimaryScreen.WorkingArea.Width,156 Height = Screen.PrimaryScreen.WorkingArea.Height157 });158 159 if (!changeCountry.Contains("请选择") && _CountryModels.Any())160 {161 OnShowTooltipInfo("初始化首页内容,开始切换国家");162 //var zips = Properties.Resources.zip.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);163 //var zip = zips.OrderBy(m => Guid.NewGuid()).First(); ...

Full Screen

Full Screen

BrowserContext.cs

Source:BrowserContext.cs Github

copy

Full Screen

...5using PuppeteerSharp.Messaging;6namespace PuppeteerSharp7{8 /// <summary>9 /// BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has10 /// a single <see cref="BrowserContext"/> used by default. The method <see cref="Browser.NewPageAsync"/> creates a <see cref="Page"/> in the default <see cref="BrowserContext"/>11 /// </summary>12 public class BrowserContext13 {14 private readonly Connection _connection;15 private readonly string _id;16 internal BrowserContext(Connection connection, Browser browser, string contextId)17 {18 _connection = connection;19 Browser = browser;20 _id = contextId;21 }22 /// <summary>23 /// Raised when the url of a target changes24 /// </summary>25 public event EventHandler<TargetChangedArgs> TargetChanged;26 /// <summary>27 /// Raised when a target is created, for example when a new page is opened by <c>window.open</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/Window/open"/> or <see cref="NewPageAsync"/>.28 /// </summary>29 public event EventHandler<TargetChangedArgs> TargetCreated;30 /// <summary>31 /// Raised when a target is destroyed, for example when a page is closed32 /// </summary>33 public event EventHandler<TargetChangedArgs> TargetDestroyed;34 /// <summary>35 /// Returns whether BrowserContext is incognito36 /// The default browser context is the only non-incognito browser context37 /// </summary>38 /// <remarks>39 /// The default browser context cannot be closed40 /// </remarks>41 public bool IsIncognito => _id != null;42 /// <summary>43 /// Gets the browser this browser context belongs to44 /// </summary>45 public Browser Browser { get; }46 /// <summary>47 /// Gets an array of all active targets inside the browser context 48 /// </summary>49 /// <returns>An array of all active targets inside the browser context</returns>50 public Target[] Targets() => Array.FindAll(Browser.Targets(), target => target.BrowserContext == this);51 /// <summary>52 /// This searches for a target in this specific browser context.53 /// <example>54 /// <code>55 /// <![CDATA[56 /// await page.EvaluateAsync("() => window.open('https://www.example.com/')");57 /// var newWindowTarget = await browserContext.WaitForTargetAsync((target) => target.Url == "https://www.example.com/");58 /// ]]>59 /// </code>60 /// </example>61 /// </summary>62 /// <param name="predicate">A function to be run for every target</param>63 /// <param name="options">options</param>64 /// <returns>Resolves to the first target found that matches the predicate function.</returns>65 public Task<Target> WaitForTargetAsync(Func<Target, bool> predicate, WaitForOptions options = null)66 => Browser.WaitForTargetAsync((target) => target.BrowserContext == this && predicate(target), options);67 /// <summary>68 /// An array of all pages inside the browser context.69 /// </summary>70 /// <returns>Task which resolves to an array of all open pages. 71 /// Non visible pages, such as <c>"background_page"</c>, will not be listed here. 72 /// You can find them using <see cref="Target.PageAsync"/>.</returns>73 public async Task<Page[]> PagesAsync()74 => (await Task.WhenAll(75 Targets().Where(t => t.Type == TargetType.Page).Select(t => t.PageAsync())).ConfigureAwait(false)76 ).Where(p => p != null).ToArray();77 /// <summary>78 /// Creates a new page79 /// </summary>80 /// <returns>Task which resolves to a new <see cref="Page"/> object</returns>81 public Task<Page> NewPageAsync() => Browser.CreatePageInContextAsync(_id);82 /// <summary>83 /// Closes the browser context. All the targets that belong to the browser context will be closed84 /// </summary>85 /// <returns>Task</returns>86 public Task CloseAsync()87 {88 if (_id == null)89 {90 throw new PuppeteerException("Non-incognito profiles cannot be closed!");91 }92 return Browser.DisposeContextAsync(_id);93 }94 /// <summary>95 /// Overrides the browser context permissions.96 /// </summary>97 /// <returns>The task.</returns>98 /// <param name="origin">The origin to grant permissions to, e.g. "https://example.com"</param>99 /// <param name="permissions">100 /// An array of permissions to grant. All permissions that are not listed here will be automatically denied.101 /// </param>102 /// <example>103 /// <![CDATA[104 /// var context = browser.DefaultBrowserContext;105 /// await context.OverridePermissionsAsync("https://html5demos.com", new List<string> {"geolocation"});106 /// ]]>107 /// </example>108 /// <seealso href="https://developer.mozilla.org/en-US/docs/Glossary/Origin"/>109 public Task OverridePermissionsAsync(string origin, IEnumerable<OverridePermission> permissions)110 => _connection.SendAsync("Browser.grantPermissions", new BrowserGrantPermissionsRequest111 {112 Origin = origin,113 BrowserContextId = _id,114 Permissions = permissions.ToArray()115 });116 /// <summary>117 /// Clears all permission overrides for the browser context.118 /// </summary>119 /// <returns>The task.</returns>120 public Task ClearPermissionOverridesAsync()121 => _connection.SendAsync("Browser.resetPermissions", new BrowserResetPermissionsRequest122 {123 BrowserContextId = _id124 });125 internal void OnTargetCreated(Browser browser, TargetChangedArgs args) => TargetCreated?.Invoke(browser, args);126 internal void OnTargetDestroyed(Browser browser, TargetChangedArgs args) => TargetDestroyed?.Invoke(browser, args);127 internal void OnTargetChanged(Browser browser, TargetChangedArgs args) => TargetChanged?.Invoke(browser, args);128 }129}...

Full Screen

Full Screen

Target.cs

Source:Target.cs Github

copy

Full Screen

...19 internal bool IsInitialized;20 internal Target(21 TargetInfo targetInfo,22 Func<TargetInfo, Task<CDPSession>> sessionFactory,23 BrowserContext browserContext)24 {25 _targetInfo = targetInfo;26 _targetId = targetInfo.TargetId;27 _sessionFactory = sessionFactory;28 BrowserContext = browserContext;29 _pageTask = null;30 InitilizedTaskWrapper = new TaskCompletionSource<bool>();31 CloseTaskWrapper = new TaskCompletionSource<bool>();32 IsInitialized = _targetInfo.Type != TargetType.Page || _targetInfo.Url != string.Empty;33 if (IsInitialized)34 {35 InitilizedTaskWrapper.SetResult(true);36 }37 }38 #region Properties39 /// <summary>40 /// Gets the URL.41 /// </summary>42 /// <value>The URL.</value>43 public string Url => _targetInfo.Url;44 /// <summary>45 /// Gets the type. It will be <see cref="TargetInfo.Type"/> if it's "page" or "service_worker". Otherwise it will be "other"46 /// </summary>47 /// <value>The type.</value>48 public TargetType Type => _targetInfo.Type;49 /// <summary>50 /// Gets the target identifier.51 /// </summary>52 /// <value>The target identifier.</value>53 public string TargetId => _targetInfo.TargetId;54 /// <summary>55 /// Get the target that opened this target56 /// </summary>57 /// <remarks>58 /// Top-level targets return <c>null</c>.59 /// </remarks>60 public Target Opener => _targetInfo.OpenerId != null ?61 Browser.TargetsMap.GetValueOrDefault(_targetInfo.OpenerId) : null;62 /// <summary>63 /// Get the browser the target belongs to.64 /// </summary>65 public Browser Browser => BrowserContext.Browser;66 /// <summary>67 /// Get the browser context the target belongs to.68 /// </summary>69 public BrowserContext BrowserContext { get; }70 internal Task<bool> InitializedTask => InitilizedTaskWrapper.Task;71 internal TaskCompletionSource<bool> InitilizedTaskWrapper { get; }72 internal Task CloseTask => CloseTaskWrapper.Task;73 internal TaskCompletionSource<bool> CloseTaskWrapper { get; }74 #endregion75 /// <summary>76 /// Creates a new <see cref="Page"/>. If the target is not <c>"page"</c> or <c>"background_page"</c> returns <c>null</c>77 /// </summary>78 /// <returns>a task that returns a new <see cref="Page"/></returns>79 public Task<Page> PageAsync()80 {81 if ((_targetInfo.Type == TargetType.Page || _targetInfo.Type == TargetType.BackgroundPage) && _pageTask == null)82 {83 _pageTask = CreatePageAsync();...

Full Screen

Full Screen

BrowserContextAccessor.cs

Source:BrowserContextAccessor.cs Github

copy

Full Screen

1using PuppeteerSharp;2using WishAndGet.Infrastructure;3namespace WishAndGet4{5 public class BrowserContextAccessor : IAsyncDisposable6 {7 private readonly AsyncLazy<BrowserContext> browserContext = new(InitializeBrowserContext);8 private static async Task<BrowserContext> InitializeBrowserContext()9 {10 var browserFetcher = new BrowserFetcher();11 await browserFetcher.DownloadAsync().AnyContext();12 var browser = await Puppeteer.LaunchAsync(13 new LaunchOptions { Headless = true });14 return await browser.CreateIncognitoBrowserContextAsync();15 }16 public Task<BrowserContext> GetBrowserContextAsync() => browserContext.Value;17 async ValueTask IAsyncDisposable.DisposeAsync()18 {19 GC.SuppressFinalize(this);20 if (browserContext.IsValueCreated)21 {22 var value = await browserContext.Value.AnyContext();23 await value.CloseAsync();24 await value.Browser.DisposeAsync().ConfigureAwait(false);25 }26 }27 }28}...

Full Screen

Full Screen

BrowserContextTests.cs

Source:BrowserContextTests.cs Github

copy

Full Screen

...4using Xunit.Abstractions;5namespace PuppeteerSharp.Tests.PageTests6{7 [Collection(TestConstants.TestFixtureCollectionName)]8 public class BrowserContextTests : PuppeteerPageBaseTest9 {10 public BrowserContextTests(ITestOutputHelper output) : base(output)11 {12 }13 [PuppeteerTest("page.spec.ts", "Page.browserContext", "should return the correct browser context instance")]14 [PuppeteerFact]15 public void ShouldReturnTheCorrectBrowserInstance() => Assert.Same(Context, Page.BrowserContext);16 }17}...

Full Screen

Full Screen

PuppeteerBrowserContextBaseTest.cs

Source:PuppeteerBrowserContextBaseTest.cs Github

copy

Full Screen

...3using Xunit;4using Xunit.Abstractions;5namespace PuppeteerSharp.Tests6{7 public class PuppeteerBrowserContextBaseTest : PuppeteerBrowserBaseTest8 {9 public PuppeteerBrowserContextBaseTest(ITestOutputHelper output) : base(output)10 {11 }12 protected BrowserContext Context { get; set; }13 public override async Task InitializeAsync()14 {15 await base.InitializeAsync();16 Context = await Browser.CreateIncognitoBrowserContextAsync();17 }18 }19}...

Full Screen

Full Screen

BrowserContext

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);26 var browser = await Puppeteer.LaunchAsync(new LaunchOptions27 {28 });29 var context = await browser.CreateIncognitoBrowserContextAsync();30 var page = await context.NewPageAsync();31 await page.ScreenshotAsync("google.png");32 await browser.CloseAsync();33 }34 }35}36using System;37using System.Threading.Tasks;38using PuppeteerSharp;39{40 {41 static async Task Main(string[] args)42 {43 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);44 var browser = await Puppeteer.LaunchAsync(new LaunchOptions45 {46 });47 var context = await browser.CreateIncognitoBrowserContextAsync();48 var page = await context.NewPageAsync();49 await page.ScreenshotAsync("google.png");50 await context.CloseAsync();51 await browser.CloseAsync();52 }53 }54}55using System;56using System.Threading.Tasks;57using PuppeteerSharp;58{59 {60 static async Task Main(string[] args)61 {62 await new BrowserFetcher().DownloadAsync(BrowserFetcher.Default

Full Screen

Full Screen

BrowserContext

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 var browser = await Puppeteer.LaunchAsync(new LaunchOptions8 {9 });10 var page = await browser.NewPageAsync();11 Console.ReadLine();12 }13 }14}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful