How to use TargetInfo class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.TargetInfo

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

Target.cs

Source: Target.cs Github

copy
1using System;
2using System.Diagnostics;
3using System.Threading.Tasks;
4using PuppeteerSharp.Helpers;
5using PuppeteerSharp.Helpers.Json;
6using PuppeteerSharp.Messaging;
7
8namespace PuppeteerSharp
9{
10    /// <summary>
11    /// Target.
12    /// </summary>
13    [DebuggerDisplay("Target {Type} - {Url}")]
14    public class Target
15    {
16        #region Private members
17        private readonly Func<Task<CDPSession>> _sessionFactory;
18        private readonly TaskCompletionSource<bool> _initializedTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
19        private Task<Worker> _workerTask;
20        #endregion
21
22        internal bool IsInitialized { get; set; }
23        internal TargetInfo TargetInfo { get; set; }
24
25        internal Target(
26            TargetInfo targetInfo,
27            Func<Task<CDPSession>> sessionFactory,
28            BrowserContext browserContext)
29        {
30            TargetInfo = targetInfo;
31            _sessionFactory = sessionFactory;
32            BrowserContext = browserContext;
33            PageTask = null;
34
35            _ = _initializedTaskWrapper.Task.ContinueWith(async initializedTask =>
36            {
37                var success = initializedTask.Result;
38                if (!success)
39                {
40                    return;
41                }
42
43                var openerPageTask = Opener?.PageTask;
44                if (openerPageTask == null || Type != TargetType.Page)
45                {
46                    return;
47                }
48                var openerPage = await openerPageTask.ConfigureAwait(false);
49                if (!openerPage.HasPopupEventListeners)
50                {
51                    return;
52                }
53                var popupPage = await PageAsync().ConfigureAwait(false);
54                openerPage.OnPopup(popupPage);
55            });
56
57            CloseTaskWrapper = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
58            IsInitialized = TargetInfo.Type != TargetType.Page || TargetInfo.Url != string.Empty;
59
60            if (IsInitialized)
61            {
62                _initializedTaskWrapper.TrySetResult(true);
63            }
64        }
65
66        #region Properties
67        /// <summary>
68        /// Gets the URL.
69        /// </summary>
70        /// <value>The URL.</value>
71        public string Url => TargetInfo.Url;
72        /// <summary>
73        /// Gets the type. It will be <see cref="TargetInfo.Type"/>.
74        /// Can be `"page"`, `"background_page"`, `"service_worker"`, `"shared_worker"`, `"browser"` or `"other"`.
75        /// </summary>
76        /// <value>The type.</value>
77        public TargetType Type => TargetInfo.Type;
78
79        /// <summary>
80        /// Gets the target identifier.
81        /// </summary>
82        /// <value>The target identifier.</value>
83        public string TargetId => TargetInfo.TargetId;
84
85        /// <summary>
86        /// Get the target that opened this target
87        /// </summary>
88        /// <remarks>
89        /// Top-level targets return <c>null</c>.
90        /// </remarks>
91        public Target Opener => TargetInfo.OpenerId != null ?
92            Browser.TargetsMap.GetValueOrDefault(TargetInfo.OpenerId) : null;
93
94        /// <summary>
95        /// Get the browser the target belongs to.
96        /// </summary>
97        public Browser Browser => BrowserContext.Browser;
98
99        /// <summary>
100        /// Get the browser context the target belongs to.
101        /// </summary>
102        public BrowserContext BrowserContext { get; }
103
104        internal Task<bool> InitializedTask => _initializedTaskWrapper.Task;
105        internal Task CloseTask => CloseTaskWrapper.Task;
106        internal TaskCompletionSource<bool> CloseTaskWrapper { get; }
107        internal Task<Page> PageTask { get; set; }
108        #endregion
109
110        /// <summary>
111        /// 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>
112        /// </summary>
113         /// <returns>a task that returns a <see cref="Page"/></returns>
114        public Task<Page> PageAsync()
115        {
116            if ((TargetInfo.Type == TargetType.Page || TargetInfo.Type == TargetType.BackgroundPage) && PageTask == null)
117            {
118                PageTask = CreatePageAsync();
119            }
120
121            return PageTask ?? Task.FromResult<Page>(null);
122        }
123
124        /// <summary>
125        /// If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.
126        /// </summary>
127        /// <returns>A task that returns a <see cref="Worker"/></returns>
128        public Task<Worker> WorkerAsync()
129        {
130            if (TargetInfo.Type != TargetType.ServiceWorker && TargetInfo.Type != TargetType.SharedWorker)
131            {
132                return null;
133            }
134            if (_workerTask == null)
135            {
136                _workerTask = WorkerInternalAsync();
137            }
138
139            return _workerTask;
140        }
141
142        private async Task<Worker> WorkerInternalAsync()
143        {
144            var client = await _sessionFactory().ConfigureAwait(false);
145            var targetAttachedWrapper = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
146            void MessageReceived(object sender, MessageEventArgs e)
147            {
148                if (e.MessageID == "Target.attachedToTarget")
149                {
150                    targetAttachedWrapper.TrySetResult(e.MessageData.ToObject<TargetAttachedToTargetResponse>(true).SessionId);
151                    client.MessageReceived -= MessageReceived;
152                }
153            }
154            client.MessageReceived += MessageReceived;
155
156            await Task.WhenAll(
157                targetAttachedWrapper.Task,
158                client.SendAsync("Target.setAutoAttach", new TargetSetAutoAttachRequest
159                {
160                    AutoAttach = true,
161                    WaitForDebuggerOnStart = false,
162                    Flatten = true
163                })).ConfigureAwait(false);
164            var session = Connection.FromSession(client).GetSession(targetAttachedWrapper.Task.Result);
165            return new Worker(
166                session,
167                TargetInfo.Url,
168                (consoleType, handles, stackTrace) => Task.CompletedTask,
169                (e) => { });
170        }
171
172        private async Task<Page> CreatePageAsync()
173        {
174            var session = await _sessionFactory().ConfigureAwait(false);
175            return await Page.CreateAsync(session, this, Browser.IgnoreHTTPSErrors, Browser.DefaultViewport, Browser.ScreenshotTaskQueue).ConfigureAwait(false);
176        }
177
178        internal void TargetInfoChanged(TargetInfo targetInfo)
179        {
180            var previousUrl = TargetInfo.Url;
181            TargetInfo = targetInfo;
182
183            if (!IsInitialized && (TargetInfo.Type != TargetType.Page || TargetInfo.Url != string.Empty))
184            {
185                IsInitialized = true;
186                _initializedTaskWrapper.TrySetResult(true);
187                return;
188            }
189
190            if (previousUrl != targetInfo.Url)
191            {
192                Browser.ChangeTarget(this);
193            }
194        }
195
196        /// <summary>
197        /// Creates a Chrome Devtools Protocol session attached to the target.
198        /// </summary>
199        /// <returns>A task that returns a <see cref="CDPSession"/></returns>
200        public Task<CDPSession> CreateCDPSessionAsync() => Browser.Connection.CreateSessionAsync(TargetInfo);
201    }
202}
203
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in TargetInfo

    No methods found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)