How to use CloseAsync method of PuppeteerSharp.BrowserContext class

Best Puppeteer-sharp code snippet using PuppeteerSharp.BrowserContext.CloseAsync

PuppeteerBrowserBuilder.cs

Source:PuppeteerBrowserBuilder.cs Github

copy

Full Screen

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

Full Screen

Full Screen

Browser.cs

Source:Browser.cs Github

copy

Full Screen

...17 /// <![CDATA[18 /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());19 /// var page = await browser.NewPageAsync();20 /// await page.GoToAsync("https://example.com");21 /// await browser.CloseAsync();22 /// ]]>23 /// </code>24 /// An example of disconnecting from and reconnecting to a <see cref="Browser"/>:25 /// <code>26 /// <![CDATA[27 /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());28 /// var browserWSEndpoint = browser.WebSocketEndpoint;29 /// browser.Disconnect();30 /// var browser2 = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = browserWSEndpoint });31 /// await browser2.CloseAsync();32 /// ]]>33 /// </code>34 /// </example>35 public class Browser : IDisposable36 {37 /// <summary>38 /// Time in milliseconds for chromium process to exit gracefully.39 /// </summary>40 private const int CloseTimeout = 5000;41 /// <summary>42 /// Initializes a new instance of the <see cref="Browser"/> class.43 /// </summary>44 /// <param name="connection">The connection</param>45 /// <param name="contextIds">The context ids></param>46 /// <param name="ignoreHTTPSErrors">The option to ignoreHTTPSErrors</param>47 /// <param name="defaultViewport">Default viewport</param>48 /// <param name="chromiumProcess">The Chromium process</param>49 public Browser(50 Connection connection,51 string[] contextIds,52 bool ignoreHTTPSErrors,53 ViewPortOptions defaultViewport,54 ChromiumProcess chromiumProcess)55 {56 Connection = connection;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))345 {346 var args = new TargetChangedArgs { Target = target };347 TargetCreated?.Invoke(this, args);348 context.OnTargetCreated(this, args);349 }350 }351 internal static async Task<Browser> CreateAsync(352 Connection connection,353 string[] contextIds,354 bool ignoreHTTPSErrors,355 ViewPortOptions defaultViewPort,356 ChromiumProcess chromiumProcess)357 {358 var browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewPort, chromiumProcess);359 await connection.SendAsync("Target.setDiscoverTargets", new360 {361 discover = true362 }).ConfigureAwait(false);363 return browser;364 }365 #endregion366 #region IDisposable367 /// <summary>368 /// Closes <see cref="Connection"/> and any Chromium <see cref="Process"/> that was369 /// created by Puppeteer.370 /// </summary>371 public void Dispose() => _ = CloseAsync();372 #endregion373 }374}...

Full Screen

Full Screen

VkBrwUserFactory.cs

Source:VkBrwUserFactory.cs Github

copy

Full Screen

...40 await userPage.SetUserAgentAsync("Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 74.0.3723.0 Safari / 537.36");41 user.Communitites = await GetCommunities(userContext, userPage, user);42 bool successParse = long.TryParse(user.ProfileLink.Split('/').LastOrDefault()?.Substring(2), out long parseResult);43 user.UserId = successParse ? parseResult : default;44 await userPage.CloseAsync();45 await userContext.CloseAsync();46 return user;47 }48 public async Task<List<VkBrwCommunity>> GetCommunities(BrowserContext userContext, Page userPage, VkBrwUser user)49 {50 List<VkBrwCommunity> nwPages = new List<VkBrwCommunity>();51 await userPage.GoToAsync(user.ProfileLink);52 ElementHandle userIsLoaded = await userPage.WaitForSelectorAsync("#page_info_wrap.page_info_wrap");53 ElementHandle[] hiddenProfileBlock = await userPage.QuerySelectorAllAsync("h5.profile_deleted_text");54 if (hiddenProfileBlock.Length == 0)55 {56 ElementHandle idolsLoaded = await userPage.WaitForSelectorAsync("#profile_idols");57 // Интересные страницы58 ElementHandle[] noteworthyPagesBlock = await userPage.QuerySelectorAllAsync("#profile_idols.module.clear.page_list_module._module");59 if (noteworthyPagesBlock.Length == 1)60 {61 ElementHandle noteworthyPages = noteworthyPagesBlock.First();62 ElementHandle[] noteworthyPagesHeaderBlock = await noteworthyPages.QuerySelectorAllAsync("a.module_header");63 if (noteworthyPagesHeaderBlock.Length == 1)64 {65 ClickOptions clickOptions = new ClickOptions { Delay = new Random().Next(30, 100) };66 ElementHandle noteworthyPagesLinkElement = noteworthyPagesHeaderBlock.First();67 await noteworthyPagesLinkElement.ClickAsync(clickOptions);68 ElementHandle noteworthyPagesIsOpened = await userPage.WaitForSelectorAsync("#fans_rowsidols.fans_rows.fans_idols");69 ElementHandle[] closeBlock = await userPage.QuerySelectorAllAsync("div.box_x_button");70 if (closeBlock.Length == 1)71 {72 ElementHandle[] pagesCountBlock = await userPage.QuerySelectorAllAsync("span.ui_box_header_cnt");73 if (pagesCountBlock.Length == 1)74 {75 ElementHandle pagesTotalCountElement = pagesCountBlock.First();76 string pagesTotalCountValue = await pagesTotalCountElement.EvaluateFunctionAsync<string>("('span', span => span.innerText)");77 if (!string.IsNullOrEmpty(pagesTotalCountValue))78 {79 bool pagesTotalCountReceived = int.TryParse(pagesTotalCountValue, out int pagesTotalCount);80 if (pagesTotalCountReceived && pagesTotalCount > 0)81 {82 ElementHandle[] pagesVisibleElements = await userPage.QuerySelectorAllAsync("div.fans_idol_row.inl_bl");83 if (pagesVisibleElements.Length < pagesTotalCount)84 {85 PressOptions pressOptions = new PressOptions { Delay = new Random().Next(20, 40)};86 await userPage.FocusAsync("input");87 await userPage.Keyboard.PressAsync("Tab", pressOptions);88 int visiblePagesCounter = pagesVisibleElements.Length;89 while (visiblePagesCounter < pagesTotalCount)90 {91 await userPage.Keyboard.PressAsync("PageDown", pressOptions);92 await Task.Delay(new Random().Next(250, 350));93 await userPage.Keyboard.PressAsync("PageDown", pressOptions);94 await Task.Delay(new Random().Next(250, 350));95 await userPage.Keyboard.PressAsync("PageDown", pressOptions);96 await Task.Delay(new Random().Next(250, 350));97 await userPage.Keyboard.PressAsync("PageDown", pressOptions);98 await Task.Delay(new Random().Next(250, 350));99 ElementHandle[] newPagesVisibleElements = await userPage.QuerySelectorAllAsync("div.fans_idol_row.inl_bl");100 if (newPagesVisibleElements.Length == visiblePagesCounter)101 {102 break;103 }104 visiblePagesCounter = newPagesVisibleElements.Length;105 }106 }107 ElementHandle[] nwPagesElements = await userPage.QuerySelectorAllAsync("div.fans_idol_info");108 foreach (var element in nwPagesElements)109 {110 VkBrwCommunity community = await GetCommunityAsync(element, userContext);111 if (community != null)112 {113 nwPages.Add(community);114 community.Users.Add(user);115 }116 }117 }118 }119 }120 ElementHandle closeButtonElement = closeBlock.First();121 await closeButtonElement.ClickAsync(clickOptions);122 }123 }124 }125 }126 else127 {128 user.HiddenProfile = true;129 ElementHandle[] pageNameElements = await userPage.QuerySelectorAllAsync("h2.page_name");130 if (pageNameElements.Length == 1)131 {132 var pageElement = pageNameElements.First();133 user.PageName = await pageElement.EvaluateFunctionAsync<string>("('h2', h2 => h2.innerText)");134 }135 }136 return nwPages;137 }138 private async Task<VkBrwCommunity> GetCommunityAsync(ElementHandle communityElement, BrowserContext userContext)139 {140 ElementHandle communityNameElement = await communityElement.QuerySelectorAsync("div.fans_idol_name");141 if (communityNameElement != null)142 {143 VkBrwCommunity nwPage = new VkBrwCommunity();144 ////await page.EvaluateFunctionAsync(@"() => {145 //// Array.from(document.querySelectorAll('li'))146 //// .find(l => l.querySelector('span').innerText === 'fire').querySelector('INPUT').click();147 ////}");148 // equals to $eval('a', a => a.innerText)149 nwPage.Name = await communityNameElement.EvaluateFunctionAsync<string>("('a', a => a.innerText)");150 ElementHandle communityLinkElement = await communityElement.QuerySelectorAsync("a.fans_idol_lnk");151 nwPage.CommunityUrl = await communityLinkElement.EvaluateFunctionAsync<string>("('a', a => a.href)");152 ElementHandle communityStatusElement = await communityElement.QuerySelectorAsync("div.fans_idol_status");153 nwPage.Status = await communityStatusElement.EvaluateFunctionAsync<string>("('div', div => div.innerText)");154 ElementHandle communitySizeElement = await communityElement.QuerySelectorAsync("div.fans_idol_size");155 nwPage.Size = await communitySizeElement.EvaluateFunctionAsync<string>("('div', div => div.innerText)");156 if (!nwPage.CommunityUrl.Contains("event"))157 {158 await GetCommunityDetailsAsync(userContext, nwPage);159 }160 return nwPage;161 }162 else163 {164 return null;165 }166 }167 private async Task GetCommunityDetailsAsync(BrowserContext browserContext, VkBrwCommunity community)168 {169 Page communityPage = await browserContext.NewPageAsync();170 ////groupPage.EvaluateFunctionAsync($"() => window.open('{groupUrl}')").GetAwaiter().GetResult();171 ////Target newWindowTarget = browser.WaitForTargetAsync(target => target.Url == "https://www.example.com/").Result;172 ////Page newPage = newWindowTarget.PageAsync().Result;173 try174 {175 await communityPage.GoToAsync(community.CommunityUrl);176 }177 catch (NavigationException)178 {179 return;180 }181 WaitForSelectorOptions waitSelectorOptions = new WaitForSelectorOptions { Timeout = 10000 };182 ElementHandle communityLoadedElement = await communityPage.WaitForSelectorAsync("div#page_wrap.scroll_fix_wrap._page_wrap", waitSelectorOptions);183 if (communityLoadedElement != null)184 {185 ElementHandle communityBlockedElement = await communityPage.QuerySelectorAsync("div.groups_blocked");186 if (communityBlockedElement != null)187 {188 community.Blocked = true;189 }190 else191 {192 community.Type = await GetCommunityTypeAsync(communityPage);193 community.CommunityId = await GetCommunityIdAsync(communityPage, community.Type);194 }195 }196 await communityPage.CloseAsync();197 }198 private async Task<CommunityTypes> GetCommunityTypeAsync(Page communityPage)199 {200 ElementHandle publicElement = await communityPage.QuerySelectorAsync("#public_followers.module.clear.people_module._module");201 if (publicElement!= null)202 {203 return CommunityTypes.Public;204 }205 ElementHandle groupElement = await communityPage.QuerySelectorAsync("#group_followers.module.clear.people_module._module");206 if (groupElement != null)207 {208 return CommunityTypes.Group;209 }210 if (communityPage.Url.Contains("event"))...

Full Screen

Full Screen

BrowserContextTests.cs

Source:BrowserContextTests.cs Github

copy

Full Screen

...21 {22 Assert.Single(Browser.BrowserContexts());23 var defaultContext = Browser.BrowserContexts()[0];24 Assert.False(defaultContext.IsIncognito);25 var exception = await Assert.ThrowsAsync<PuppeteerException>(defaultContext.CloseAsync);26 Assert.Same(defaultContext, Browser.DefaultContext);27 Assert.Contains("cannot be closed", exception.Message);28 }29 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should create new incognito context")]30 [PuppeteerFact]31 public async Task ShouldCreateNewIncognitoContext()32 {33 Assert.Single(Browser.BrowserContexts());34 var context = await Browser.CreateIncognitoBrowserContextAsync();35 Assert.True(context.IsIncognito);36 Assert.Equal(2, Browser.BrowserContexts().Length);37 Assert.Contains(context, Browser.BrowserContexts());38 await context.CloseAsync();39 Assert.Single(Browser.BrowserContexts());40 }41 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should close all belonging targets once closing context")]42 [PuppeteerFact]43 public async Task ShouldCloseAllBelongingTargetsOnceClosingContext()44 {45 Assert.Single((await Browser.PagesAsync()));46 var context = await Browser.CreateIncognitoBrowserContextAsync();47 await context.NewPageAsync();48 Assert.Equal(2, (await Browser.PagesAsync()).Length);49 Assert.Single((await context.PagesAsync()));50 await context.CloseAsync();51 Assert.Single((await Browser.PagesAsync()));52 }53 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "window.open should use parent tab context")]54 [SkipBrowserFact(skipFirefox: true)]55 public async Task WindowOpenShouldUseParentTabContext()56 {57 var context = await Browser.CreateIncognitoBrowserContextAsync();58 var page = await context.NewPageAsync();59 await page.GoToAsync(TestConstants.EmptyPage);60 var popupTargetCompletion = new TaskCompletionSource<Target>();61 Browser.TargetCreated += (_, e) => popupTargetCompletion.SetResult(e.Target);62 await Task.WhenAll(63 popupTargetCompletion.Task,64 page.EvaluateFunctionAsync("url => window.open(url)", TestConstants.EmptyPage)65 );66 var popupTarget = await popupTargetCompletion.Task;67 Assert.Same(context, popupTarget.BrowserContext);68 await context.CloseAsync();69 }70 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should fire target events")]71 [SkipBrowserFact(skipFirefox: true)]72 public async Task ShouldFireTargetEvents()73 {74 var context = await Browser.CreateIncognitoBrowserContextAsync();75 var events = new List<string>();76 context.TargetCreated += (_, e) => events.Add("CREATED: " + e.Target.Url);77 context.TargetChanged += (_, e) => events.Add("CHANGED: " + e.Target.Url);78 context.TargetDestroyed += (_, e) => events.Add("DESTROYED: " + e.Target.Url);79 var page = await context.NewPageAsync();80 await page.GoToAsync(TestConstants.EmptyPage);81 await page.CloseAsync();82 Assert.Equal(new[] {83 $"CREATED: {TestConstants.AboutBlank}",84 $"CHANGED: {TestConstants.EmptyPage}",85 $"DESTROYED: {TestConstants.EmptyPage}"86 }, events);87 await context.CloseAsync();88 }89 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should isolate local storage and cookies")]90 [PuppeteerFact]91 public async Task ShouldIsolateLocalStorageAndCookies()92 {93 // Create two incognito contexts.94 var context1 = await Browser.CreateIncognitoBrowserContextAsync();95 var context2 = await Browser.CreateIncognitoBrowserContextAsync();96 Assert.Empty(context1.Targets());97 Assert.Empty(context2.Targets());98 // Create a page in first incognito context.99 var page1 = await context1.NewPageAsync();100 await page1.GoToAsync(TestConstants.EmptyPage);101 await page1.EvaluateExpressionAsync(@"{102 localStorage.setItem('name', 'page1');103 document.cookie = 'name=page1';104 }");105 Assert.Single(context1.Targets());106 Assert.Empty(context2.Targets());107 // Create a page in second incognito context.108 var page2 = await context2.NewPageAsync();109 await page2.GoToAsync(TestConstants.EmptyPage);110 await page2.EvaluateExpressionAsync(@"{111 localStorage.setItem('name', 'page2');112 document.cookie = 'name=page2';113 }");114 Assert.Single(context1.Targets());115 Assert.Equal(page1.Target, context1.Targets()[0]);116 Assert.Single(context2.Targets());117 Assert.Equal(page2.Target, context2.Targets()[0]);118 // Make sure pages don't share localstorage or cookies.119 Assert.Equal("page1", await page1.EvaluateExpressionAsync<string>("localStorage.getItem('name')"));120 Assert.Equal("name=page1", await page1.EvaluateExpressionAsync<string>("document.cookie"));121 Assert.Equal("page2", await page2.EvaluateExpressionAsync<string>("localStorage.getItem('name')"));122 Assert.Equal("name=page2", await page2.EvaluateExpressionAsync<string>("document.cookie"));123 // Cleanup contexts.124 await Task.WhenAll(context1.CloseAsync(), context2.CloseAsync());125 Assert.Single(Browser.BrowserContexts());126 }127 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should work across sessions")]128 [SkipBrowserFact(skipFirefox: true)]129 public async Task ShouldWorkAcrossSessions()130 {131 Assert.Single(Browser.BrowserContexts());132 var context = await Browser.CreateIncognitoBrowserContextAsync();133 Assert.Equal(2, Browser.BrowserContexts().Length);134 var remoteBrowser = await Puppeteer.ConnectAsync(new ConnectOptions135 {136 BrowserWSEndpoint = Browser.WebSocketEndpoint137 });138 var contexts = remoteBrowser.BrowserContexts();139 Assert.Equal(2, contexts.Length);140 remoteBrowser.Disconnect();141 await context.CloseAsync();142 }143 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should wait for target")]144 [SkipBrowserFact(skipFirefox: true)]145 public async Task ShouldWaitForTarget()146 {147 var context = await Browser.CreateIncognitoBrowserContextAsync();148 var targetPromise = context.WaitForTargetAsync((target) => target.Url == TestConstants.EmptyPage);149 var page = await context.NewPageAsync();150 await page.GoToAsync(TestConstants.EmptyPage);151 var promiseTarget = await targetPromise;152 var targetPage = await promiseTarget.PageAsync();153 Assert.Equal(targetPage, page);154 await context.CloseAsync();155 }156 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should timeout waiting for non existant target")]157 [PuppeteerFact]158 public async Task ShouldTimeoutWaitingForNonExistantTarget()159 {160 var context = await Browser.CreateIncognitoBrowserContextAsync();161 await Assert.ThrowsAsync<TimeoutException>(()162 => context.WaitForTargetAsync((target) => target.Url == TestConstants.EmptyPage, new WaitForOptions { Timeout = 1 }));163 await context.CloseAsync();164 }165 }166}...

Full Screen

Full Screen

BrowserContext.cs

Source:BrowserContext.cs Github

copy

Full Screen

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

Full Screen

Full Screen

BrowserContextOverridePermissionsTests.cs

Source:BrowserContextOverridePermissionsTests.cs Github

copy

Full Screen

...99 Assert.Equal("granted", await GetPermissionAsync(otherPage, "geolocation"));100 await Context.ClearPermissionOverridesAsync();101 Assert.Equal("prompt", await GetPermissionAsync(Page, "geolocation"));102 Assert.Equal("granted", await GetPermissionAsync(otherPage, "geolocation"));103 await otherContext.CloseAsync();104 }105 }106}...

Full Screen

Full Screen

BrowserContextAccessor.cs

Source:BrowserContextAccessor.cs Github

copy

Full Screen

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

PuppeteerPageBaseTest.cs

Source:PuppeteerPageBaseTest.cs Github

copy

Full Screen

...19 }20 public async Task DisposeAsync()21 {22 await TearDown();23 await Page.CloseAsync();24 await Browser.CloseAsync();25 }26 protected virtual async Task SetUp()27 {28 await Task.CompletedTask;29 }30 protected virtual async Task TearDown()31 {32 await Task.CompletedTask;33 }34 }35}...

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var options = new LaunchOptions { Headless = false };9 using (var browser = await Puppeteer.LaunchAsync(options))10 {11 var page = await browser.NewPageAsync();12 await page.CloseAsync();13 }14 }15 }16}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.WaitForSelectorAsync("input[name=q]");13 await page.TypeAsync("input[name=q]", "PuppeteerSharp");14 await page.ClickAsync("input[name=btnK]");15 await page.WaitForSelectorAsync("a[href='

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync("screenshot.png");13 await browser.CloseAsync();14 Console.WriteLine("Hello World!");15 }16 }17}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 CloseAsyncExample().GetAwaiter().GetResult();9 }10 static async Task CloseAsyncExample()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 });15 var page = await browser.NewPageAsync();16 await page.WaitForTimeoutAsync(5000);17 await browser.CloseAsync();18 }19 }20}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.CloseAsync();13 await browser.CloseAsync();14 }15 }16}17using System;18using System.Threading.Tasks;19using PuppeteerSharp;20{21 {22 static async Task Main(string[] args)23 {24 var browser = await Puppeteer.LaunchAsync(new LaunchOptions25 {26 });27 var page = await browser.NewPageAsync();28 await page.CloseAsync();29 await browser.CloseAsync();30 }31 }32}33using System;34using System.Threading.Tasks;35using PuppeteerSharp;36{37 {38 static async Task Main(string[] args)39 {40 var browser = await Puppeteer.LaunchAsync(new LaunchOptions41 {42 });43 var page = await browser.NewPageAsync();44 await page.CloseAsync();45 await browser.CloseAsync();46 }47 }48}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System.Threading.Tasks;2using PuppeteerSharp;3{4 {5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 }))11 using (var page = await browser.NewPageAsync())12 {13 await page.ScreenshotAsync("google.png");14 }15 await browser.CloseAsync();16 }17 }18}

Full Screen

Full Screen

CloseAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });9 var page = await browser.NewPageAsync();10 await page.ScreenshotAsync("google.png");11 await browser.CloseAsync();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