Best Puppeteer-sharp code snippet using PuppeteerSharp.States.InitialState
ChromiumProcess.cs
Source:ChromiumProcess.cs
...287 /// </remarks>288 private abstract class State289 {290 #region Predefined states291 public static readonly State Initial = new InitialState();292 private static readonly StartingState Starting = new StartingState();293 private static readonly StartedState Started = new StartedState();294 private static readonly ExitingState Exiting = new ExitingState();295 private static readonly KillingState Killing = new KillingState();296 private static readonly ExitedState Exited = new ExitedState();297 private static readonly DisposedState Disposed = new DisposedState();298 #endregion299 #region Properties300 public bool IsExiting => this == Killing || this == Exiting;301 public bool IsExited => this == Exited || this == Disposed;302 #endregion303 #region Methods304 /// <summary>305 /// Attempts thread-safe transitions from a given state to this state.306 /// </summary>307 /// <param name="p">The Chromium process</param>308 /// <param name="fromState">The state from which state transition takes place</param>309 /// <returns>Returns <c>true</c> if transition is successful, or <c>false</c> if transition310 /// cannot be made because current state does not equal <paramref name="fromState"/>.</returns>311 protected bool TryEnter(ChromiumProcess p, State fromState)312 {313 if (Interlocked.CompareExchange(ref p._currentState, this, fromState) == fromState)314 {315 fromState.Leave(p);316 return true;317 }318 return false;319 }320 /// <summary>321 /// Notifies that state machine is about to transition to another state.322 /// </summary>323 /// <param name="p">The Chromium process</param>324 protected virtual void Leave(ChromiumProcess p)325 { }326 /// <summary>327 /// Handles process start request.328 /// </summary>329 /// <param name="p">The Chromium process</param>330 /// <returns></returns>331 public virtual Task StartAsync(ChromiumProcess p) => Task.FromException(InvalidOperation("start"));332 /// <summary>333 /// Handles process exit request.334 /// </summary>335 /// <param name="p">The Chromium process</param>336 /// <param name="timeout">The maximum waiting time for a graceful process exit.</param>337 /// <returns></returns>338 public virtual Task ExitAsync(ChromiumProcess p, TimeSpan timeout) => Task.FromException(InvalidOperation("exit"));339 /// <summary>340 /// Handles process kill request.341 /// </summary>342 /// <param name="p">The Chromium process</param>343 /// <returns></returns>344 public virtual Task KillAsync(ChromiumProcess p) => Task.FromException(InvalidOperation("kill"));345 /// <summary>346 /// Handles wait for process exit request.347 /// </summary>348 /// <param name="p">The Chromium process</param>349 /// <returns></returns>350 public virtual Task WaitForExitAsync(ChromiumProcess p) => p._exitCompletionSource.Task;351 /// <summary>352 /// Handles disposal of process and temporary user directory353 /// </summary>354 /// <param name="p"></param>355 public virtual void Dispose(ChromiumProcess p) => Disposed.EnterFrom(p, this);356 public override string ToString()357 {358 var name = GetType().Name;359 return name.Substring(0, name.Length - "State".Length);360 }361 private Exception InvalidOperation(string operationName)362 => new InvalidOperationException($"Cannot {operationName} in state {this}");363 /// <summary>364 /// Kills process if it is still alive.365 /// </summary>366 /// <param name="p"></param>367 private static void Kill(ChromiumProcess p)368 {369 try370 {371 if (!p.Process.HasExited)372 {373 p.Process.Kill();374 }375 }376 catch (InvalidOperationException)377 {378 // Ignore379 }380 }381 #endregion382 #region Concrete state classes383 private class InitialState : State384 {385 public override Task StartAsync(ChromiumProcess p) => Starting.EnterFromAsync(p, this);386 public override Task ExitAsync(ChromiumProcess p, TimeSpan timeout)387 {388 Exited.EnterFrom(p, this);389 return Task.CompletedTask;390 }391 public override Task KillAsync(ChromiumProcess p)392 {393 Exited.EnterFrom(p, this);394 return Task.CompletedTask;395 }396 public override Task WaitForExitAsync(ChromiumProcess p) => Task.FromException(InvalidOperation("wait for exit"));397 }...
LauncherBase.cs
Source:LauncherBase.cs
...209 #region Predefined states210 /// <summary>211 /// Set initial state.212 /// </summary>213 public static readonly State Initial = new InitialState();214 private static readonly StartingState Starting = new StartingState();215 private static readonly StartedState Started = new StartedState();216 private static readonly ExitingState Exiting = new ExitingState();217 private static readonly KillingState Killing = new KillingState();218 private static readonly ExitedState Exited = new ExitedState();219 private static readonly DisposedState Disposed = new DisposedState();220 #endregion221 #region Properties222 /// <summary>223 /// Get If process exists.224 /// </summary>225 public bool IsExiting => this == Killing || this == Exiting;226 /// <summary>227 /// Get If process is exited.228 /// </summary>229 public bool IsExited => this == Exited || this == Disposed;230 #endregion231 #region Methods232 /// <summary>233 /// Attempts thread-safe transitions from a given state to this state.234 /// </summary>235 /// <param name="p">The Base process</param>236 /// <param name="fromState">The state from which state transition takes place</param>237 /// <returns>Returns <c>true</c> if transition is successful, or <c>false</c> if transition238 /// cannot be made because current state does not equal <paramref name="fromState"/>.</returns>239 protected bool TryEnter(LauncherBase p, State fromState)240 {241 if (Interlocked.CompareExchange(ref p._currentState, this, fromState) == fromState)242 {243 fromState.Leave(p);244 return true;245 }246 return false;247 }248 /// <summary>249 /// Notifies that state machine is about to transition to another state.250 /// </summary>251 /// <param name="p">The Base process</param>252 protected virtual void Leave(LauncherBase p)253 {254 }255 /// <summary>256 /// Handles process start request.257 /// </summary>258 /// <param name="p">The Base process</param>259 /// <returns></returns>260 public virtual Task StartAsync(LauncherBase p) => Task.FromException(InvalidOperation("start"));261 /// <summary>262 /// Handles process exit request.263 /// </summary>264 /// <param name="p">The Base process</param>265 /// <param name="timeout">The maximum waiting time for a graceful process exit.</param>266 /// <returns></returns>267 public virtual Task ExitAsync(LauncherBase p, TimeSpan timeout) => Task.FromException(InvalidOperation("exit"));268 /// <summary>269 /// Handles process kill request.270 /// </summary>271 /// <param name="p">The Base process</param>272 /// <returns></returns>273 public virtual Task KillAsync(LauncherBase p) => Task.FromException(InvalidOperation("kill"));274 /// <summary>275 /// Handles wait for process exit request.276 /// </summary>277 /// <param name="p">The Base process</param>278 /// <returns></returns>279 public virtual Task WaitForExitAsync(LauncherBase p) => p._exitCompletionSource.Task;280 /// <summary>281 /// Handles disposal of process and temporary user directory282 /// </summary>283 /// <param name="p"></param>284 public virtual void Dispose(LauncherBase p) => Disposed.EnterFrom(p, this);285 /// <inheritdoc />286 public override string ToString()287 {288 string name = GetType().Name;289 return name.Substring(0, name.Length - "State".Length);290 }291 private Exception InvalidOperation(string operationName)292 => new InvalidOperationException($"Cannot {operationName} in state {this}");293 /// <summary>294 /// Kills process if it is still alive.295 /// </summary>296 /// <param name="p"></param>297 private static void Kill(LauncherBase p)298 {299 try300 {301 if (!p.Process.HasExited)302 {303 p.Process.Kill();304 }305 }306 catch (InvalidOperationException)307 {308 // Ignore309 }310 }311 #endregion312 #region Concrete state classes313 private class InitialState : State314 {315 public override Task StartAsync(LauncherBase p) => Starting.EnterFromAsync(p, this);316 public override Task ExitAsync(LauncherBase p, TimeSpan timeout)317 {318 Exited.EnterFrom(p, this);319 return Task.CompletedTask;320 }321 public override Task KillAsync(LauncherBase p)322 {323 Exited.EnterFrom(p, this);324 return Task.CompletedTask;325 }326 public override Task WaitForExitAsync(LauncherBase p) => Task.FromException(InvalidOperation("wait for exit"));327 }...
IdleOverrideTests.cs
Source:IdleOverrideTests.cs
1using System.Collections.Generic;2using System.Linq;3using System.Threading.Tasks;4using PuppeteerSharp.Tests.Attributes;5using PuppeteerSharp.Xunit;6using Xunit;7using Xunit.Abstractions;8namespace PuppeteerSharp.Tests.IdleOverrideTests9{10 [Collection(TestConstants.TestFixtureCollectionName)]11 public class IdleOverrideTests : PuppeteerPageBaseTest12 {13 public IdleOverrideTests(ITestOutputHelper output) : base(output)14 {15 }16 private async Task<string> GetIdleStateAsync()17 {18 var stateElement = await Page.QuerySelectorAsync("#state");19 return await Page.EvaluateFunctionAsync<string>(20 @"(element) => {21 return element.innerText;22 }",23 stateElement);24 }25 private async Task VerifyStateAsync(string expectedState)26 {27 var actualState = await GetIdleStateAsync();28 Assert.Equal(expectedState, actualState);29 }30 [PuppeteerTest("idle_override.spec.ts", "Emulate idle state", "changing idle state emulation causes change of the IdleDetector state")]31 [SkipBrowserFact(skipFirefox: true)]32 public async Task ChangingIdleStateEmulationCausesChangeOfTheIdleDetectorState()33 {34 await Context.OverridePermissionsAsync(35 TestConstants.ServerUrl + "/idle-detector.html",36 new[]37 {38 OverridePermission.IdleDetection,39 });40 await Page.GoToAsync(TestConstants.ServerUrl+ "/idle-detector.html");41 // Store initial state, as soon as it is not guaranteed to be `active, unlocked`.42 var initialState = await GetIdleStateAsync();43 // Emulate Idle states and verify IdleDetector updates state accordingly.44 await Page.EmulateIdleStateAsync(new EmulateIdleOverrides {45 IsUserActive = false,46 IsScreenUnlocked = false,47 });48 await VerifyStateAsync("Idle state: idle, locked.");49 await Page.EmulateIdleStateAsync(new EmulateIdleOverrides {50 IsUserActive = true,51 IsScreenUnlocked = false,52 });53 await VerifyStateAsync("Idle state: active, locked.");54 await Page.EmulateIdleStateAsync(new EmulateIdleOverrides {55 IsUserActive = true,56 IsScreenUnlocked = true,57 });58 await VerifyStateAsync("Idle state: active, unlocked.");59 await Page.EmulateIdleStateAsync(new EmulateIdleOverrides {60 IsUserActive = false,61 IsScreenUnlocked = true,62 });63 await VerifyStateAsync("Idle state: idle, unlocked.");64 // Remove Idle emulation and verify IdleDetector is in initial state.65 await Page.EmulateIdleStateAsync();66 await VerifyStateAsync(initialState);67 // Emulate idle state again after removing emulation.68 await Page.EmulateIdleStateAsync(new EmulateIdleOverrides {69 IsUserActive = false,70 IsScreenUnlocked = false,71 });72 await VerifyStateAsync("Idle state: idle, locked.");73 // Remove emulation second time.74 await Page.EmulateIdleStateAsync();75 await VerifyStateAsync(initialState);76 }77 }78}...
StateManager.cs
Source:StateManager.cs
...6 {7 private State _currentState;8 public StateManager()9 {10 Initial = new InitialState(this);11 Starting = new ChromiumStartingState(this);12 Started = new StartedState(this);13 Exiting = new ExitingState(this);14 Killing = new KillingState(this);15 Exited = new ExitedState(this);16 Disposed = new DisposedState(this);17 CurrentState = Initial;18 }19 public State CurrentState20 {21 get => _currentState;22 set => _currentState = value;23 }24 internal State Initial { get; set; }...
InitialState.cs
Source:InitialState.cs
1using System;2using System.Threading.Tasks;3namespace PuppeteerSharp.States4{5 internal class InitialState : State6 {7 public InitialState(StateManager stateManager) : base(stateManager)8 {9 }10 public override Task StartAsync(LauncherBase p) => StateManager.Starting.EnterFromAsync(p, this, TimeSpan.Zero);11 public override Task ExitAsync(LauncherBase p, TimeSpan timeout)12 {13 StateManager.Exited.EnterFromAsync(p, this);14 return Task.CompletedTask;15 }16 public override Task KillAsync(LauncherBase p)17 {18 StateManager.Exited.EnterFromAsync(p, this);19 return Task.CompletedTask;20 }21 public override Task WaitForExitAsync(LauncherBase p) => Task.FromException(InvalidOperation("wait for exit"));...
InitialState
Using AI Code Generation
1var options = new LaunchOptions { Headless = false };2var browser = await Puppeteer.LaunchAsync(options);3var page = await browser.NewPageAsync();4var initialState = new InitialState();5initialState.SetViewport(new ViewPortOptions { Width = 1280, Height = 800 });6await page.SetViewportAsync(new ViewPortOptions { Width = 1280, Height = 800 });7await page.ScreenshotAsync("example.png");8await browser.CloseAsync();9var options = new LaunchOptions { Headless = false };10var browser = await Puppeteer.LaunchAsync(options);11var page = await browser.NewPageAsync();12var initialState = new InitialState();13initialState.SetViewport(new ViewPortOptions { Width = 1280, Height = 800 });14await page.SetViewportAsync(new ViewPortOptions { Width = 1280, Height = 800 });15await page.ScreenshotAsync("example.png");16await browser.CloseAsync();17var options = new LaunchOptions { Headless = false };18var browser = await Puppeteer.LaunchAsync(options);19var page = await browser.NewPageAsync();20var initialState = new InitialState();21initialState.SetViewport(new ViewPortOptions { Width = 1280, Height = 800 });22await page.SetViewportAsync(new ViewPortOptions { Width = 1280, Height = 800 });23await page.ScreenshotAsync("example.png");24await browser.CloseAsync();25var options = new LaunchOptions { Headless = false };26var browser = await Puppeteer.LaunchAsync(options);27var page = await browser.NewPageAsync();28var initialState = new InitialState();29initialState.SetViewport(new ViewPortOptions { Width = 1280, Height = 800 });
InitialState
Using AI Code Generation
1var initialState = new InitialState();2initialState.SetViewport(new ViewPortOptions() { Width = 1200, Height = 800 });3initialState.SetUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36");4initialState.SetExtraHTTPHeaders(new Dictionary<string, string>() { { "Accept-Language", "en-US" } });5initialState.SetOffline(false);6initialState.SetGeolocation(new Geolocation() { Latitude = 37.422, Longitude = 122.084 });7initialState.SetPermissions(new string[] { "geolocation" });8initialState.SetHasTouch(false);9initialState.SetColorScheme(ColorScheme.Light);10initialState.SetEmulateMedia(MediaScreenType.Screen);11initialState.SetMediaFeatures(new MediaFeature[] { new MediaFeature() { Name = "prefers-color-scheme", Value = "dark" } });12initialState.SetTimezoneId("Europe/Moscow");13initialState.SetLocale("ru-RU");14initialState.SetIsMobile(false);15initialState.SetHasTouch(false);16initialState.SetHasTouch(false);17{18 Args = new string[] { "--start-maximized" },19};20var browser = await Puppeteer.LaunchAsync(options);21{22 Args = new string[] { "--start-maximized" },23 UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36",24 ExtraHTTPHeaders = new Dictionary<string, string>() { { "Accept-Language", "en-US" } },25 Geolocation = new Geolocation() { Latitude = 37.422, Longitude = 122.084 },26 Permissions = new string[] { "geolocation" },
InitialState
Using AI Code Generation
1var puppeteer = require('puppeteer');2var initialState = require('puppeteersharp.states');3var fs = require('fs');4var path = require('path');5(async () => {6 const browser = await puppeteer.launch({headless: false});7 const page = await browser.newPage();8 await page.screenshot({path: 'example.png'});9 await page.screenshot({path: 'example-element.png', selector: '#example'});10 await page.screenshot({path: 'example.png', width: 800, height: 600});11 await page.screenshot({path: 'example.png', width: 800, height: 600});12 await page.screenshot({path: 'example.png', width: 800, height: 600});13 await page.screenshot({path: 'example.png', width: 800, height: 600});14 await page.screenshot({path: 'example.png', width: 800, height: 600});15 await page.screenshot({path: 'example.png', width: 800, height: 600});16 await page.screenshot({path: 'example.png', width: 800, height: 600});17 await page.screenshot({path: 'example.png', width: 800, height: 600});18 await page.screenshot({path: 'example.png', width: 800, height: 600});19 await page.screenshot({path: 'example
InitialState
Using AI Code Generation
1using PuppeteerSharp.States;2await page.SetContentAsync("<!DOCTYPE html><html><head><title>Test</title></head><body><h1>Hello World</h1></body></html>");3await page.SetStateAsync(new InitialState4{5});6using PuppeteerSharp.States;7await page.SetStateAsync(new InitialState8{9});10using PuppeteerSharp.States;11await page.SetStateAsync(new InitialState12{13});14using PuppeteerSharp.States;15await page.SetStateAsync(new InitialState16{17});18using PuppeteerSharp.States;
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!