How to use TargetInfo class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.TargetInfo

Browser.cs

Source:Browser.cs Github

copy

Full Screen

...366 case "Target.targetDestroyed":367 await DestroyTargetAsync(e.MessageData.ToObject<TargetDestroyedResponse>(true)).ConfigureAwait(false);368 return;369 case "Target.targetInfoChanged":370 ChangeTargetInfo(e.MessageData.ToObject<TargetCreatedResponse>(true));371 return;372 }373 }374 catch (Exception ex)375 {376 string message = $"Browser failed to process {e.MessageID}. {ex.Message}. {ex.StackTrace}";377 Connection.Close(message);378 }379 }380 private void ChangeTargetInfo(TargetCreatedResponse e)381 {382 if (!TargetsMap.ContainsKey(e.TargetInfo.TargetId))383 {384 throw new InvalidTargetException("Target should exists before ChangeTargetInfo");385 }386 var target = TargetsMap[e.TargetInfo.TargetId];387 target.TargetInfoChanged(e.TargetInfo);388 }389 private async Task DestroyTargetAsync(TargetDestroyedResponse e)390 {391 if (!TargetsMap.ContainsKey(e.TargetId))392 {393 throw new InvalidTargetException("Target should exists before DestroyTarget");394 }395 var target = TargetsMap[e.TargetId];396 TargetsMap.Remove(e.TargetId);397 target.CloseTaskWrapper.TrySetResult(true);398 if (await target.InitializedTask.ConfigureAwait(false))399 {400 var args = new TargetChangedArgs { Target = target };401 TargetDestroyed?.Invoke(this, args);402 target.BrowserContext.OnTargetDestroyed(this, args);403 }404 }405 private async Task CreateTargetAsync(TargetCreatedResponse e)406 {407 var targetInfo = e.TargetInfo;408 string browserContextId = targetInfo.BrowserContextId;409 if (!(browserContextId != null && _contexts.TryGetValue(browserContextId, out var context)))410 {411 context = DefaultContext;412 }413 var target = new Target(414 e.TargetInfo,415 () => Connection.CreateSessionAsync(targetInfo),416 context);417 TargetsMap[e.TargetInfo.TargetId] = target;418 if (await target.InitializedTask.ConfigureAwait(false))419 {420 var args = new TargetChangedArgs { Target = target };421 TargetCreated?.Invoke(this, args);422 context.OnTargetCreated(this, args);423 }424 }425 internal static async Task<Browser> CreateAsync(426 Connection connection,427 string[] contextIds,428 bool ignoreHTTPSErrors,429 ViewPortOptions defaultViewPort,430 LauncherBase launcher)431 {...

Full Screen

Full Screen

Connection.cs

Source:Connection.cs Github

copy

Full Screen

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

Target.cs

Source:Target.cs Github

copy

Full Screen

...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 var targetAttachedWrapper = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);128 void MessageReceived(object sender, MessageEventArgs e)129 {130 if (e.MessageID == "Target.attachedToTarget")131 {132 targetAttachedWrapper.TrySetResult(e.MessageData.ToObject<TargetAttachedToTargetResponse>(true).SessionId);133 client.MessageReceived -= MessageReceived;134 }135 }136 client.MessageReceived += MessageReceived;137 await Task.WhenAll(138 targetAttachedWrapper.Task,139 client.SendAsync("Target.setAutoAttach", new TargetSetAutoAttachRequest140 {141 AutoAttach = true,142 WaitForDebuggerOnStart = false,143 Flatten = true144 })).ConfigureAwait(false);145 var session = Connection.FromSession(client).GetSession(targetAttachedWrapper.Task.Result);146 return new Worker(147 session,148 TargetInfo.Url,149 (consoleType, handles, stackTrace) => Task.CompletedTask,150 (e) => { });151 }152 private async Task<Page> CreatePageAsync()153 {154 var session = await _sessionFactory().ConfigureAwait(false);155 return await Page.CreateAsync(session, this, Browser.IgnoreHTTPSErrors, Browser.DefaultViewport, Browser.ScreenshotTaskQueue).ConfigureAwait(false);156 }157 internal void TargetInfoChanged(TargetInfo targetInfo)158 {159 var previousUrl = TargetInfo.Url;160 TargetInfo = targetInfo;161 if (!IsInitialized && (TargetInfo.Type != TargetType.Page || TargetInfo.Url != string.Empty))162 {163 IsInitialized = true;164 _initializedTaskWrapper.TrySetResult(true);165 return;166 }167 if (previousUrl != targetInfo.Url)168 {169 Browser.ChangeTarget(this);170 }171 }172 /// <summary>173 /// Creates a Chrome Devtools Protocol session attached to the target.174 /// </summary>175 /// <returns>A task that returns a <see cref="CDPSession"/></returns>176 public Task<CDPSession> CreateCDPSessionAsync() => Browser.Connection.CreateSessionAsync(TargetInfo);177 }178}...

Full Screen

Full Screen

TargetInfo.cs

Source:TargetInfo.cs Github

copy

Full Screen

...3{4 /// <summary>5 /// Target info.6 /// </summary>7 public class TargetInfo8 {9 /// <summary>10 /// Initializes a new instance of the <see cref="TargetInfo"/> class.11 /// </summary>12 public TargetInfo()13 {14 }15 /// <summary>16 /// Initializes a new instance of the <see cref="TargetInfo"/> class.17 /// </summary>18 /// <param name="targetInfo">Target info.</param>19 public TargetInfo(dynamic targetInfo)20 {21 Type = targetInfo.type;22 Url = targetInfo.url;23 TargetId = targetInfo.targetId;24 SourceObject = targetInfo;25 }26 /// <summary>27 /// Gets or sets the type.28 /// </summary>29 /// <value>The type.</value>30 public string Type { get; internal set; }31 /// <summary>32 /// Gets or sets the URL.33 /// </summary>...

Full Screen

Full Screen

TargetChangedArgs.cs

Source:TargetChangedArgs.cs Github

copy

Full Screen

...11 /// <summary>12 /// Gets or sets the target info.13 /// </summary>14 /// <value>The target info.</value>15 public TargetInfo TargetInfo { get; internal set; }16 /// <summary>17 /// Gets or sets the target.18 /// </summary>19 /// <value>The target.</value>20 public Target Target { get; internal set; }21 }...

Full Screen

Full Screen

ConnectionResponseParams.cs

Source:ConnectionResponseParams.cs Github

copy

Full Screen

...4 {5 public string SessionId { get; set; }6 public string Message { get; set; }7 public string Stream { get; set; }8 public TargetInfo TargetInfo { get; set; }9 }...

Full Screen

Full Screen

TargetAttachedToTargetResponse.cs

Source:TargetAttachedToTargetResponse.cs Github

copy

Full Screen

1namespace PuppeteerSharp.Messaging2{3 internal class TargetAttachedToTargetResponse4 {5 public TargetInfo TargetInfo { get; set; }6 public string SessionId { get; set; }7 }8}...

Full Screen

Full Screen

TargetCreatedResponse.cs

Source:TargetCreatedResponse.cs Github

copy

Full Screen

1namespace PuppeteerSharp.Messaging2{3 internal class TargetCreatedResponse4 {5 public TargetInfo TargetInfo { get; set; }6 }...

Full Screen

Full Screen

TargetInfo

Using AI Code Generation

copy

Full Screen

1{2 public string TargetId { get; set; }3 public string Type { get; set; }4 public string Title { get; set; }5 public string Url { get; set; }6 public bool? IsClosed { get; set; }7 public string BrowserContextId { get; set; }8}9{10 public string TargetId { get; set; }11 public string Type { get; set; }12 public string Title { get; set; }13 public string Url { get; set; }14 public bool? IsClosed { get; set; }15 public string BrowserContextId { get; set; }16}

Full Screen

Full Screen

TargetInfo

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 public string TargetId { get; set; }7 public string Type { get; set; }8 public string Title { get; set; }9 public string Url { get; set; }10 public bool Attached { get; set; }11 public string BrowserContextId { get; set; }12 }13}14using PuppeteerSharp;15using System;16using System.Threading.Tasks;17{18 {19 public string TargetId { get; set; }20 public string Type { get; set; }21 public string Title { get; set; }22 public string Url { get; set; }23 public bool Attached { get; set; }24 public string BrowserContextId { get; set; }25 }26}27using PuppeteerSharp;28using System;29using System.Threading.Tasks;30{31 {32 public string TargetId { get; set; }33 public string Type { get; set; }34 public string Title { get; set; }35 public string Url { get; set; }36 public bool Attached { get; set; }37 public string BrowserContextId { get; set; }38 }39}40using PuppeteerSharp;41using System;42using System.Threading.Tasks;43{44 {45 public string TargetId { get; set; }46 public string Type { get; set; }47 public string Title { get; set; }48 public string Url { get; set; }49 public bool Attached { get; set; }50 public string BrowserContextId { get; set; }51 }52}53using PuppeteerSharp;54using System;55using System.Threading.Tasks;56{57 {58 public string TargetId { get; set; }59 public string Type { get; set

Full Screen

Full Screen

TargetInfo

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var options = new LaunchOptions { Headless = true };9 using (var browser = await Puppeteer.LaunchAsync(options))10 {11 var page = await browser.NewPageAsync();12 string title = await page.EvaluateFunctionAsync<string>("() => document.title");13 Console.WriteLine("Page title is: " + title);14 string url = await page.EvaluateFunctionAsync<string>("() => document.URL");15 Console.WriteLine("Page url is: " + url);16 string html = await page.EvaluateFunctionAsync<string>("() => document.documentElement.outerHTML");17 Console.WriteLine("Page html is: " + html);18 }19 }20 }21}22using PuppeteerSharp;23using System;24using System.Threading.Tasks;25{26 {27 static async Task Main(string[] args)28 {29 var options = new LaunchOptions { Headless = true };30 using (var browser = await Puppeteer.LaunchAsync(options))31 {32 var page = await browser.NewPageAsync();33 string title = await page.EvaluateFunctionAsync<string>("() => document.title");34 Console.WriteLine("Page title is: " + title);35 string url = await page.EvaluateFunctionAsync<string>("() => document.URL");36 Console.WriteLine("Page url is: " + url);37 string html = await page.EvaluateFunctionAsync<string>("() => document.documentElement.outerHTML");38 Console.WriteLine("Page html is: " + html);39 }40 }41 }42}

Full Screen

Full Screen

TargetInfo

Using AI Code Generation

copy

Full Screen

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

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