How to use CDPSession class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.CDPSession

Connection.cs

Source:Connection.cs Github

copy

Full Screen

...24 Transport = transport;25 Transport.MessageReceived += Transport_MessageReceived;26 Transport.Closed += Transport_Closed;27 _callbacks = new ConcurrentDictionary<int, MessageTask>();28 _sessions = new ConcurrentDictionary<string, CDPSession>();29 _asyncSessions = new AsyncDictionaryHelper<string, CDPSession>(_sessions, "Session {0} not found");30 }31 #region Private Members32 private int _lastId;33 private readonly ConcurrentDictionary<int, MessageTask> _callbacks;34 private readonly ConcurrentDictionary<string, CDPSession> _sessions;35 private readonly AsyncDictionaryHelper<string, CDPSession> _asyncSessions;36 #endregion37 #region Properties38 /// <summary>39 /// Gets the WebSocket URL.40 /// </summary>41 /// <value>The URL.</value>42 public string Url { get; }43 /// <summary>44 /// Gets the sleep time when a message is received.45 /// </summary>46 /// <value>The delay.</value>47 public int Delay { get; }48 /// <summary>49 /// Gets the Connection transport.50 /// </summary>51 /// <value>Connection transport.</value>52 public IConnectionTransport Transport { get; }53 /// <summary>54 /// Occurs when the connection is closed.55 /// </summary>56 public event EventHandler Disconnected;57 /// <summary>58 /// Occurs when a message from chromium is received.59 /// </summary>60 public event EventHandler<MessageEventArgs> MessageReceived;61 /// <summary>62 /// Gets or sets a value indicating whether this <see cref="Connection"/> is closed.63 /// </summary>64 /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>65 public bool IsClosed { get; internal set; }66 /// <summary>67 /// Connection close reason.68 /// </summary>69 public string CloseReason { get; private set; }70 #endregion71 #region Public Methods72 internal int GetMessageID() => Interlocked.Increment(ref _lastId);73 internal Task RawSendASync(int id, string method, object args, string sessionId = null)74 {75 return Transport.SendAsync(JsonConvert.SerializeObject(76 new ConnectionRequest77 {78 Id = id,79 Method = method,80 Params = args,81 SessionId = sessionId82 },83 JsonHelper.DefaultJsonSerializerSettings));84 }85 internal async Task<JObject> SendAsync(string method, object args = null, bool waitForCallback = true)86 {87 if (IsClosed)88 {89 throw new TargetClosedException($"Protocol error({method}): Target closed.", CloseReason);90 }91 var id = GetMessageID();92 MessageTask callback = null;93 if (waitForCallback)94 {95 callback = new MessageTask96 {97 TaskWrapper = new TaskCompletionSource<JObject>(),98 Method = method99 };100 _callbacks[id] = callback;101 }102 await RawSendASync(id, method, args).ConfigureAwait(false);103 return waitForCallback ? await callback.TaskWrapper.Task.ConfigureAwait(false) : null;104 }105 internal async Task<T> SendAsync<T>(string method, object args = null)106 {107 var response = await SendAsync(method, args).ConfigureAwait(false);108 return response.ToObject<T>(true);109 }110 internal async Task<CDPSession> CreateSessionAsync(TargetInfo targetInfo)111 {112 var sessionId = (await SendAsync<TargetAttachToTargetResponse>("Target.attachToTarget", new TargetAttachToTargetRequest113 {114 TargetId = targetInfo.TargetId,115 Flatten = true116 }).ConfigureAwait(false)).SessionId;117 return await GetSessionAsync(sessionId).ConfigureAwait(false);118 }119 internal bool HasPendingCallbacks() => _callbacks.Count != 0;120 #endregion121 internal void Close(string closeReason)122 {123 if (IsClosed)124 {125 return;126 }127 IsClosed = true;128 CloseReason = closeReason;129 Transport.StopReading();130 Disconnected?.Invoke(this, new EventArgs());131 foreach (var session in _sessions.Values.ToArray())132 {133 session.Close(closeReason);134 }135 _sessions.Clear();136 foreach (var response in _callbacks.Values.ToArray())137 {138 response.TaskWrapper.TrySetException(new TargetClosedException(139 $"Protocol error({response.Method}): Target closed.",140 closeReason));141 }142 _callbacks.Clear();143 }144 internal static Connection FromSession(CDPSession session) => session.Connection;145 internal CDPSession GetSession(string sessionId) => _sessions.GetValueOrDefault(sessionId);146 internal Task<CDPSession> GetSessionAsync(string sessionId) => _asyncSessions.GetItemAsync(sessionId);147 #region Private Methods148 private async void Transport_MessageReceived(object sender, MessageReceivedEventArgs e)149 => await _callbackQueue.Enqueue(() => ProcessMessage(e)).ConfigureAwait(false);150 private async Task ProcessMessage(MessageReceivedEventArgs e)151 {152 try153 {154 var response = e.Message;155 ConnectionResponse obj = null;156 if (response.Length > 0 && Delay > 0)157 {158 await Task.Delay(Delay).ConfigureAwait(false);159 }160 try161 {162 obj = JsonConvert.DeserializeObject<ConnectionResponse>(response, JsonHelper.DefaultJsonSerializerSettings);163 }164 catch (JsonException)165 {166 return;167 }168 ProcessIncomingMessage(obj);169 }170 catch (Exception ex)171 {172 var message = $"Connection failed to process {e.Message}. {ex.Message}. {ex.StackTrace}";173 Close(message);174 }175 }176 private void ProcessIncomingMessage(ConnectionResponse obj)177 {178 var method = obj.Method;179 var param = obj.Params?.ToObject<ConnectionResponseParams>();180 if (method == "Target.attachedToTarget")181 {182 var sessionId = param.SessionId;183 var session = new CDPSession(this, param.TargetInfo.Type, sessionId);184 _asyncSessions.AddItem(sessionId, session);185 }186 else if (method == "Target.detachedFromTarget")187 {188 var sessionId = param.SessionId;189 if (_sessions.TryRemove(sessionId, out var session) && !session.IsClosed)190 {191 session.Close("Target.detachedFromTarget");192 }193 }194 if (!string.IsNullOrEmpty(obj.SessionId))195 {196 var session = GetSession(obj.SessionId);197 session.OnMessage(obj);...

Full Screen

Full Screen

CDPSession.cs

Source:CDPSession.cs Github

copy

Full Screen

...7using System.Threading.Tasks;8namespace PuppeteerSharp9{10 /// <summary>11 /// The CDPSession instances are used to talk raw Chrome Devtools Protocol:12 /// * Protocol methods can be called with <see cref="CDPSession.SendAsync(string, object, bool)"/> method.13 /// * Protocol events, using the <see cref="CDPSession.MessageReceived"/> event.14 ///15 /// Documentation on DevTools Protocol can be found here: <see href="https://chromedevtools.github.io/devtools-protocol/"/>.16 ///17 /// <code>18 /// <![CDATA[19 /// var client = await Page.Target.CreateCDPSessionAsync();20 /// await client.SendAsync("Animation.enable");21 /// client.MessageReceived += (sender, e) =>22 /// {23 /// if (e.MessageID == "Animation.animationCreated")24 /// {25 /// Console.WriteLine("Animation created!");26 /// }27 /// };28 /// JObject response = await client.SendAsync("Animation.getPlaybackRate");29 /// Console.WriteLine("playback rate is " + response.playbackRate);30 /// await client.SendAsync("Animation.setPlaybackRate", new31 /// {32 /// playbackRate = Convert.ToInt32(response.playbackRate / 2)33 /// });34 /// ]]></code>35 /// </summary>36 public class CDPSession37 {38 internal CDPSession(Connection connection, TargetType targetType, string sessionId)39 {40 Connection = connection;41 TargetType = targetType;42 SessionId = sessionId;43 _callbacks = new ConcurrentDictionary<int, MessageTask>();44 }45 #region Private Members46 private readonly ConcurrentDictionary<int, MessageTask> _callbacks;47 #endregion48 #region Properties49 /// <summary>50 /// Gets the target type.51 /// </summary>52 /// <value>The target type.</value>53 public TargetType TargetType { get; }54 /// <summary>55 /// Gets the session identifier.56 /// </summary>57 /// <value>The session identifier.</value>58 public string SessionId { get; }59 /// <summary>60 /// Gets the connection.61 /// </summary>62 /// <value>The connection.</value>63 internal Connection Connection { get; private set; }64 /// <summary>65 /// Occurs when message received from Chromium.66 /// </summary>67 public event EventHandler<MessageEventArgs> MessageReceived;68 /// <summary>69 /// Occurs when the connection is closed.70 /// </summary>71 public event EventHandler Disconnected;72 /// <summary>73 /// Gets or sets a value indicating whether this <see cref="CDPSession"/> is closed.74 /// </summary>75 /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>76 public bool IsClosed { get; internal set; }77 /// <summary>78 /// Connection close reason.79 /// </summary>80 public string CloseReason { get; private set; }81 /// <summary>82 /// Gets the logger factory.83 /// </summary>84 /// <value>The logger factory.</value>85 #endregion86 #region Public Methods87 internal void Send(string method, object args = null)...

Full Screen

Full Screen

Target.cs

Source:Target.cs Github

copy

Full Screen

...12 [DebuggerDisplay("Target {Type} - {Url}")]13 public class Target14 {15 #region Private members16 private readonly Func<Task<CDPSession>> _sessionFactory;17 private readonly TaskCompletionSource<bool> _initializedTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);18 private Task<Worker> _workerTask;19 #endregion20 internal bool IsInitialized { get; set; }21 internal TargetInfo TargetInfo { get; set; }22 internal Target(23 TargetInfo targetInfo,24 Func<Task<CDPSession>> sessionFactory,25 BrowserContext browserContext)26 {27 TargetInfo = targetInfo;28 _sessionFactory = sessionFactory;29 BrowserContext = browserContext;30 PageTask = null;31 _ = _initializedTaskWrapper.Task.ContinueWith(async initializedTask =>32 {33 var success = initializedTask.Result;34 if (!success)35 {36 return;37 }38 var openerPageTask = Opener?.PageTask;39 if (openerPageTask == null || Type != TargetType.Page)40 {41 return;42 }43 var openerPage = await openerPageTask.ConfigureAwait(false);44 if (!openerPage.HasPopupEventListeners)45 {46 return;47 }48 var popupPage = await PageAsync().ConfigureAwait(false);49 openerPage.OnPopup(popupPage);50 });51 CloseTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);52 IsInitialized = TargetInfo.Type != TargetType.Page || TargetInfo.Url != string.Empty;53 if (IsInitialized)54 {55 _initializedTaskWrapper.TrySetResult(true);56 }57 }58 #region Properties59 /// <summary>60 /// Gets the URL.61 /// </summary>62 /// <value>The URL.</value>63 public string Url => TargetInfo.Url;64 /// <summary>65 /// Gets the type. It will be <see cref="TargetInfo.Type"/>.66 /// Can be `"page"`, `"background_page"`, `"service_worker"`, `"shared_worker"`, `"browser"` or `"other"`.67 /// </summary>68 /// <value>The type.</value>69 public TargetType Type => TargetInfo.Type;70 /// <summary>71 /// Gets the target identifier.72 /// </summary>73 /// <value>The target identifier.</value>74 public string TargetId => TargetInfo.TargetId;75 /// <summary>76 /// Get the target that opened this target77 /// </summary>78 /// <remarks>79 /// Top-level targets return <c>null</c>.80 /// </remarks>81 public Target Opener => TargetInfo.OpenerId != null ?82 Browser.TargetsMap.GetValueOrDefault(TargetInfo.OpenerId) : null;83 /// <summary>84 /// Get the browser the target belongs to.85 /// </summary>86 public Browser Browser => BrowserContext.Browser;87 /// <summary>88 /// Get the browser context the target belongs to.89 /// </summary>90 public BrowserContext BrowserContext { get; }91 internal Task<bool> InitializedTask => _initializedTaskWrapper.Task;92 internal Task CloseTask => CloseTaskWrapper.Task;93 internal TaskCompletionSource<bool> CloseTaskWrapper { get; }94 internal Task<Page> PageTask { get; set; }95 #endregion96 /// <summary>97 /// Returns the <see cref="Page"/> associated with the target. If the target is not <c>"page"</c> or <c>"background_page"</c> returns <c>null</c>98 /// </summary>99 /// <returns>a task that returns a <see cref="Page"/></returns>100 public Task<Page> PageAsync()101 {102 if ((TargetInfo.Type == TargetType.Page || TargetInfo.Type == TargetType.BackgroundPage) && PageTask == null)103 {104 PageTask = CreatePageAsync();105 }106 return PageTask ?? Task.FromResult<Page>(null);107 }108 /// <summary>109 /// If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.110 /// </summary>111 /// <returns>A task that returns a <see cref="Worker"/></returns>112 public Task<Worker> WorkerAsync()113 {114 if (TargetInfo.Type != TargetType.ServiceWorker && TargetInfo.Type != TargetType.SharedWorker)115 {116 return null;117 }118 if (_workerTask == null)119 {120 _workerTask = WorkerInternalAsync();121 }122 return _workerTask;123 }124 private async Task<Worker> WorkerInternalAsync()125 {126 var client = await _sessionFactory().ConfigureAwait(false);127 return new Worker(128 client,129 TargetInfo.Url,130 (consoleType, handles, stackTrace) => Task.CompletedTask,131 (e) => { });132 }133 private async Task<Page> CreatePageAsync()134 {135 var session = await _sessionFactory().ConfigureAwait(false);136 return await Page.CreateAsync(session, this, Browser.IgnoreHTTPSErrors, Browser.DefaultViewport, Browser.ScreenshotTaskQueue).ConfigureAwait(false);137 }138 internal void TargetInfoChanged(TargetInfo targetInfo)139 {140 var previousUrl = TargetInfo.Url;141 TargetInfo = targetInfo;142 if (!IsInitialized && (TargetInfo.Type != TargetType.Page || TargetInfo.Url != string.Empty))143 {144 IsInitialized = true;145 _initializedTaskWrapper.TrySetResult(true);146 return;147 }148 if (previousUrl != targetInfo.Url)149 {150 Browser.ChangeTarget(this);151 }152 }153 /// <summary>154 /// Creates a Chrome Devtools Protocol session attached to the target.155 /// </summary>156 /// <returns>A task that returns a <see cref="CDPSession"/></returns>157 public Task<CDPSession> CreateCDPSessionAsync() => Browser.Connection.CreateSessionAsync(TargetInfo);158 }159}...

Full Screen

Full Screen

Worker.cs

Source:Worker.cs Github

copy

Full Screen

...21 /// </code>22 /// </example>23 public class Worker24 {25 private readonly CDPSession _client;26 private ExecutionContext _executionContext;27 // private readonly Func<ConsoleType, JSHandle[], StackTrace, Task> _consoleAPICalled;28 private readonly Action<EvaluateExceptionResponseDetails> _exceptionThrown;29 private readonly TaskCompletionSource<ExecutionContext> _executionContextCallback;30 private Func<ExecutionContext, RemoteObject, JSHandle> _jsHandleFactory;31 internal Worker(32 CDPSession client,33 string url,34 Func<ConsoleType, JSHandle[], Task> consoleAPICalled,35 Action<EvaluateExceptionResponseDetails> exceptionThrown)36 {37 _client = client;38 Url = url;39 _exceptionThrown = exceptionThrown;40 _client.MessageReceived += OnMessageReceived;41 _executionContextCallback = new TaskCompletionSource<ExecutionContext>(TaskCreationOptions.RunContinuationsAsynchronously);42 _ = _client.SendAsync("Runtime.enable").ContinueWith(task =>43 {44 });45 _ = _client.SendAsync("Log.enable").ContinueWith(task =>46 {...

Full Screen

Full Screen

CreateCDPSessionTests.cs

Source:CreateCDPSessionTests.cs Github

copy

Full Screen

...7using Xunit.Abstractions;8namespace PuppeteerSharp.Tests.TargetTests9{10 [Collection(TestConstants.TestFixtureCollectionName)]11 public class CreateCDPSessionTests : PuppeteerPageBaseTest12 {13 public CreateCDPSessionTests(ITestOutputHelper output) : base(output)14 {15 }16 [Fact]17 public async Task ShouldWork()18 {19 var client = await Page.Target.CreateCDPSessionAsync();20 await Task.WhenAll(21 client.SendAsync("Runtime.enable"),22 client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest { Expression = "window.foo = 'bar'" })23 );24 var foo = await Page.EvaluateExpressionAsync<string>("window.foo");25 Assert.Equal("bar", foo);26 }27 [Fact]28 public async Task ShouldSendEvents()29 {30 var client = await Page.Target.CreateCDPSessionAsync();31 await client.SendAsync("Network.enable");32 var events = new List<object>();33 client.MessageReceived += (sender, e) =>34 {35 if (e.MessageID == "Network.requestWillBeSent")36 {37 events.Add(e.MessageData);38 }39 };40 await Page.GoToAsync(TestConstants.EmptyPage);41 Assert.Single(events);42 }43 [Fact]44 public async Task ShouldEnableAndDisableDomainsIndependently()45 {46 var client = await Page.Target.CreateCDPSessionAsync();47 await client.SendAsync("Runtime.enable");48 await client.SendAsync("Debugger.enable");49 // JS coverage enables and then disables Debugger domain.50 await Page.Coverage.StartJSCoverageAsync();51 await Page.Coverage.StopJSCoverageAsync();52 // generate a script in page and wait for the event.53 var eventTask = WaitEvent(client, "Debugger.scriptParsed");54 await Task.WhenAll(55 eventTask,56 Page.EvaluateExpressionAsync("//# sourceURL=foo.js")57 );58 // expect events to be dispatched.59 Assert.Equal("foo.js", eventTask.Result["url"].Value<string>());60 }61 [Fact]62 public async Task ShouldBeAbleToDetachSession()63 {64 var client = await Page.Target.CreateCDPSessionAsync();65 await client.SendAsync("Runtime.enable");66 var evalResponse = await client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest67 {68 Expression = "1 + 2",69 ReturnByValue = true70 });71 Assert.Equal(3, evalResponse["result"]["value"].ToObject<int>());72 await client.DetachAsync();73 var exception = await Assert.ThrowsAnyAsync<Exception>(()74 => client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest75 {76 Expression = "3 + 1",77 ReturnByValue = true78 }));79 Assert.Contains("Session closed.", exception.Message);80 }81 [Fact]82 public async Task ShouldThrowNiceErrors()83 {84 var client = await Page.Target.CreateCDPSessionAsync();85 async Task TheSourceOfTheProblems() => await client.SendAsync("ThisCommand.DoesNotExist");86 var exception = await Assert.ThrowsAsync<MessageException>(async () =>87 {88 await TheSourceOfTheProblems();89 });90 Assert.Contains("TheSourceOfTheProblems", exception.StackTrace);91 Assert.Contains("ThisCommand.DoesNotExist", exception.Message);92 }93 }94}...

Full Screen

Full Screen

EmulationManager.cs

Source:EmulationManager.cs Github

copy

Full Screen

...4namespace PuppeteerSharp5{6 internal class EmulationManager7 {8 private readonly CDPSession _client;9 private string _injectedTouchScriptId;10 private bool _emulatingMobile;11 public EmulationManager(CDPSession client)12 {13 _client = client;14 }15 internal async Task<bool> EmulateViewport(CDPSession client, ViewPortOptions viewport)16 {17 var mobile = viewport.IsMobile;18 var width = viewport.Width;19 var height = viewport.Height;20 var deviceScaleFactor = viewport.DeviceScaleFactor;21 ScreenOrientation screenOrientation = viewport.IsLandscape ?22 new ScreenOrientation23 {24 Angle = 90,25 Type = ScreenOrientationType.LandscapePrimary26 } :27 new ScreenOrientation28 {29 Angle = 0,...

Full Screen

Full Screen

Touchscreen.cs

Source:Touchscreen.cs Github

copy

Full Screen

...7 /// Provides methods to interact with the touch screen8 /// </summary>9 public class Touchscreen10 {11 private readonly CDPSession _client;12 private readonly Keyboard _keyboard;13 /// <summary>14 /// Initializes a new instance of the <see cref="Touchscreen"/> class.15 /// </summary>16 /// <param name="client">The client</param>17 /// <param name="keyboard">The keyboard</param>18 public Touchscreen(CDPSession client, Keyboard keyboard)19 {20 _client = client;21 _keyboard = keyboard;22 }23 /// <summary>24 /// Dispatches a <c>touchstart</c> and <c>touchend</c> event.25 /// </summary>26 /// <param name="x"></param>27 /// <param name="y"></param>28 /// <returns>Task</returns>29 /// <seealso cref="Page.TapAsync(string)"/>30 public async Task TapAsync(decimal x, decimal y)31 {32 // Touches appear to be lost during the first frame after navigation....

Full Screen

Full Screen

ElementHandle.cs

Source:ElementHandle.cs Github

copy

Full Screen

...8 public class ElementHandle : JSHandle9 {10 internal ElementHandle(11 ExecutionContext context,12 CDPSession client,13 RemoteObject remoteObject)14 : base(context, client, remoteObject) { }15 }16}...

Full Screen

Full Screen

CDPSession

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 Args = new string[] { "--start-maximized" }11 });12 var page = await browser.NewPageAsync();13 var client = await page.Target.CreateCDPSessionAsync();14 await client.SendAsync("Page.setDownloadBehavior", new { behavior = "allow", downloadPath = @"C:\Users\Downloads" });15 await page.ScreenshotAsync(@"C:\Users\Downloads\1.png");16 await browser.CloseAsync();17 }18 }19}

Full Screen

Full Screen

CDPSession

Using AI Code Generation

copy

Full Screen

1{2 public static void Main(string[] args)3 {4 var task = MainAsync();5 task.Wait();6 }7 public static async Task MainAsync()8 {9 {10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 using (var page = await browser.NewPageAsync())13 {14 var client = await page.Target.CreateCDPSessionAsync();15 await client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new16 {17 source = @"Object.defineProperty(navigator, 'webdriver', { get: () => undefined })"18 });19 }20 }21}22{23 public static void Main(string[] args)24 {25 var task = MainAsync();26 task.Wait();27 }28 public static async Task MainAsync()29 {30 {31 };32 using (var browser = await Puppeteer.LaunchAsync(options))33 using (var page = await browser.NewPageAsync())34 {35 var client = await page.Target.CreateCDPSessionAsync();36 await client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new37 {38 source = @"Object.defineProperty(navigator, 'webdriver', { get: () => undefined })"39 });40 }41 }42}43{44 public static void Main(string[] args)45 {46 var task = MainAsync();47 task.Wait();48 }49 public static async Task MainAsync()50 {51 {52 };53 using (var browser = await Puppeteer.LaunchAsync(options))54 using (var page = await browser.NewPageAsync())55 {

Full Screen

Full Screen

CDPSession

Using AI Code Generation

copy

Full Screen

1var chrome = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--start-maximized" }4});5var page = await chrome.NewPageAsync();6await page.WaitForSelectorAsync("input[name='q']");7await page.TypeAsync("input[name='q']", "PuppeteerSharp");8await page.ClickAsync("input[name='btnK']");9await page.WaitForSelectorAsync("a[href='

Full Screen

Full Screen

CDPSession

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.Text.Json;5using System.Collections.Generic;6{7 {8 static void Main(string[] args)9 {10 {11 run().Wait();12 }13 catch (Exception ex)14 {15 Console.WriteLine(ex.Message);16 }17 {18 Console.WriteLine("Press any key to exit.");19 Console.ReadKey();20 }21 }22 static async Task run()23 {24 var options = new LaunchOptions { Headless = false };25 var browser = await Puppeteer.LaunchAsync(options);26 var page = await browser.NewPageAsync();27 await page.WaitForSelectorAsync("input[name='q']");28 var client = page.Target.CreateCDPSessionAsync().Result;29 var response = await client.SendAsync("Network.enable");30 {31 {"requestId", "1234567890"},32 {"frameId", "1234567890"},33 {"loaderId", "1234567890"},34 {"type", "Document"},35 {"method", "GET"},36 {"timeStamp", 1234567890},37 {"hasUserGesture", false}38 };39 var requestJson = JsonSerializer.Serialize(request);40 response = await client.SendAsync("Network.requestWillBeSent", request);41 await page.ScreenshotAsync("google.png");42 }43 }44}45using System;46using System.Threading.Tasks;47using PuppeteerSharp;48using System.Text.Json;49using System.Collections.Generic;50{51 {52 static void Main(string[] args)53 {54 {55 run().Wait();56 }57 catch (Exception ex)58 {59 Console.WriteLine(ex.Message);60 }61 {62 Console.WriteLine("Press any key to exit.");63 Console.ReadKey();64 }65 }66 static async Task run()67 {68 var options = new LaunchOptions { Headless = false };69 var browser = await Puppeteer.LaunchAsync(options);70 var page = await browser.NewPageAsync();

Full Screen

Full Screen

CDPSession

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 private static async Task Main(string[] args)7 {8 {9 Args = new string[] { "--window-size=1920,1080" }10 };11 var browser = await Puppeteer.LaunchAsync(options);12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 var client = await page.Target.CreateCDPSessionAsync();15 await client.SendAsync("Page.enable");16 await client.SendAsync("Page.startScreencast", new { format = "png", everyNthFrame = 1 });17 client.MessageReceived += async (sender, e) =>18 {19 if (e.Method == "Page.screencastFrame")20 {21 var base64 = e.Message["data"].ToString();22 var buffer = Convert.FromBase64String(base64);23 await System.IO.File.WriteAllBytesAsync($"screenshot_{Guid.NewGuid()}.png", buffer);24 }25 };26 await Task.Delay(10000);27 await browser.CloseAsync();28 }29 }30}31using System;32using System.Threading.Tasks;33using PuppeteerSharp;34{35 {36 private static async Task Main(string[] args)37 {38 {39 Args = new string[] { "--window-size=1920,1080" }40 };41 var browser = await Puppeteer.LaunchAsync(options);42 var page = await browser.NewPageAsync();43 await page.ScreenshotAsync("google.png");44 await page.StartScreencastAsync(new PageStartScreencastOptions { Format = "png", EveryNthFrame = 1 });45 page.ScreencastFrame += async (sender, e) =>

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