How to use ChangeTarget method of PuppeteerSharp.Browser class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Browser.ChangeTarget

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;
5
6namespace PuppeteerSharp
7{
8    /// <summary>
9    /// Target.
10    /// </summary>
11    [DebuggerDisplay("Target {Type} - {Url}")]
12    public class Target
13    {
14        #region Private members
15        private TargetInfo _targetInfo;
16        private readonly string _targetId;
17        private readonly Func<TargetInfo, Task<CDPSession>> _sessionFactory;
18        private Task<Page> _pageTask;
19        #endregion
20
21        internal bool IsInitialized;
22
23        internal Target(
24            TargetInfo targetInfo,
25            Func<TargetInfo, Task<CDPSession>> sessionFactory,
26            BrowserContext browserContext)
27        {
28            _targetInfo = targetInfo;
29            _targetId = targetInfo.TargetId;
30            _sessionFactory = sessionFactory;
31            BrowserContext = browserContext;
32            _pageTask = null;
33
34            InitilizedTaskWrapper = new TaskCompletionSource<bool>();
35            CloseTaskWrapper = new TaskCompletionSource<bool>();
36            IsInitialized = _targetInfo.Type != TargetType.Page || _targetInfo.Url != string.Empty;
37
38            if (IsInitialized)
39            {
40                InitilizedTaskWrapper.SetResult(true);
41            }
42        }
43
44        #region Properties
45        /// <summary>
46        /// Gets the URL.
47        /// </summary>
48        /// <value>The URL.</value>
49        public string Url => _targetInfo.Url;
50        /// <summary>
51        /// Gets the type. It will be <see cref="TargetInfo.Type"/> if it's "page" or "service_worker". Otherwise it will be "other"
52        /// </summary>
53        /// <value>The type.</value>
54        public TargetType Type => _targetInfo.Type;
55
56        /// <summary>
57        /// Gets the target identifier.
58        /// </summary>
59        /// <value>The target identifier.</value>
60        public string TargetId => _targetInfo.TargetId;
61
62        /// <summary>
63        /// Get the target that opened this target
64        /// </summary>
65        /// <remarks>
66        /// Top-level targets return <c>null</c>.
67        /// </remarks>
68        public Target Opener => _targetInfo.OpenerId != null ?
69            Browser.TargetsMap.GetValueOrDefault(_targetInfo.OpenerId) : null;
70
71        /// <summary>
72        /// Get the browser the target belongs to.
73        /// </summary>
74        public Browser Browser => BrowserContext.Browser;
75
76        /// <summary>
77        /// Get the browser context the target belongs to.
78        /// </summary>
79        public BrowserContext BrowserContext { get; }
80
81        internal Task<bool> InitializedTask => InitilizedTaskWrapper.Task;
82        internal TaskCompletionSource<bool> InitilizedTaskWrapper { get; }
83        internal Task CloseTask => CloseTaskWrapper.Task;
84        internal TaskCompletionSource<bool> CloseTaskWrapper { get; }
85        #endregion
86
87        /// <summary>
88        /// Creates a new <see cref="Page"/>. If the target is not <c>"page"</c> or <c>"background_page"</c> returns <c>null</c>
89        /// </summary>
90        /// <returns>a task that returns a new <see cref="Page"/></returns>
91        public Task<Page> PageAsync()
92        {
93            if ((_targetInfo.Type == TargetType.Page || _targetInfo.Type == TargetType.BackgroundPage) && _pageTask == null)
94            {
95                _pageTask = CreatePageAsync();
96            }
97
98            return _pageTask ?? Task.FromResult<Page>(null);
99        }
100
101        private async Task<Page> CreatePageAsync()
102        {
103            var session = await _sessionFactory(_targetInfo).ConfigureAwait(false);
104            return await Page.CreateAsync(session, this, Browser.IgnoreHTTPSErrors, Browser.DefaultViewport, Browser.ScreenshotTaskQueue).ConfigureAwait(false);
105        }
106
107        internal void TargetInfoChanged(TargetInfo targetInfo)
108        {
109            var previousUrl = _targetInfo.Url;
110            _targetInfo = targetInfo;
111
112            if (!IsInitialized && (_targetInfo.Type != TargetType.Page || _targetInfo.Url != string.Empty))
113            {
114                IsInitialized = true;
115                InitilizedTaskWrapper.SetResult(true);
116                return;
117            }
118
119            if (previousUrl != targetInfo.Url)
120            {
121                Browser.ChangeTarget(this);
122            }
123        }
124
125        /// <summary>
126        /// Creates a Chrome Devtools Protocol session attached to the target.
127        /// </summary>
128        /// <returns>A task that returns a <see cref="CDPSession"/></returns>
129        public Task<CDPSession> CreateCDPSessionAsync() => Browser.Connection.CreateSessionAsync(_targetInfo);
130    }
131}
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

Trigger ChangeTarget code on LambdaTest Cloud Grid

Execute automation tests with ChangeTarget on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

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)