How to use TargetChangedArgs class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.TargetChangedArgs

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

ChromiumHelper.cs

Source: ChromiumHelper.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Linq;
5using System.Reflection;
6using System.Text;
7using System.Threading.Tasks;
8using PuppeteerSharp;
9
10namespace Qzone.Util
11{
12    public class ChromiumHelper
13    {
14        private Browser browser;
15        private Page page;
16
17        private static object obj = new object();
18        private static ChromiumHelper helper;
19
20        public Browser ChromiumBrowser 
21        { 
22            get 
23            {
24                return browser;
25            }
26        }
27
28        public Page CurrentBrowserTab
29        {
30            get
31            {
32                return page;
33            }
34        }
35
36        public ChromiumHelper()
37        {
38            
39        }
40
41        public static ChromiumHelper GetChromium()
42        {
43            if(helper == null)
44            {
45                lock(obj)
46                {
47                    if (helper == null)
48                        helper = new ChromiumHelper();
49                }
50            }
51
52            return helper;
53        }
54
55        public async Task InitBrowser()
56        {
57            if (browser == null)
58            {
59                await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);
60
61                browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions
62                {
63                    Headless = true
64                });
65
66                page = await browser.NewPageAsync();
67            }
68        }
69
70        public async Task LaunchUrl(string url)
71        {
72            if(page != null)
73            {
74                await page.GoToAsync(url);
75            }
76        }
77
78        /// <summary>
79        /// 二维码超时,点击刷新
80        /// </summary>
81        public async void RefreshQR()
82        {
83            if(page != null)
84            {
85                await page.ReloadAsync();
86            }
87        }
88
89        public async Task<Stream> Screenshot()
90        {
91            if(page != null)
92            {
93                return await page.ScreenshotStreamAsync();
94            }
95
96            return null;
97        }      
98        
99        public void SetTargetChangedHandler(EventHandler<TargetChangedArgs> eventHandler)
100        {
101            if(browser != null)
102            {
103                browser.TargetChanged += eventHandler;
104            }
105        }
106
107        public void RemoveTargetChangedHandler(EventHandler<TargetChangedArgs> eventHandler)
108        {
109            if (browser != null)
110            {
111                browser.TargetChanged -= eventHandler;
112            }
113        }
114
115        public async Task<string> GetHtmlSource()
116        {
117            if(page != null)
118            {
119                return await page.GetContentAsync();
120            }
121
122            return "";
123        }
124
125        public async Task<string> GetHtmlSource(string url)
126        {
127            await LaunchUrl(url);
128            return await GetHtmlSource();
129        }
130
131        public async Task<string> GetS_Key()
132        {
133            if(page != null)
134            {
135                var cookies = await page.GetCookiesAsync();
136                var sKey = cookies.Where(x => x.Name == "skey").FirstOrDefault();
137
138                if (sKey == null)
139                    return "";
140                else
141                    return sKey.Value;
142            }
143
144            return "";
145        }
146
147        public async void FreeChromiumHelper()
148        {
149            if (browser != null)
150            {
151                await browser.CloseAsync();
152                browser.Disconnect();
153                browser.Dispose();              
154            }
155        }
156    }
157}
158
Full Screen

BrowserContext.cs

Source: BrowserContext.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading.Tasks;
5using PuppeteerSharp.Messaging;
6
7namespace PuppeteerSharp
8{
9    /// <summary>
10    /// BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has
11    /// a single <see cref="BrowserContext"/> used by default. The method <see cref="Browser.NewPageAsync"/> creates a <see cref="Page"/> in the default <see cref="BrowserContext"/>
12    /// </summary>
13    public class BrowserContext
14    {
15        private readonly Connection _connection;
16        private readonly string _id;
17
18        internal BrowserContext(Connection connection, Browser browser, string contextId)
19        {
20            _connection = connection;
21            Browser = browser;
22            _id = contextId;
23        }
24
25        /// <summary>
26        /// Raised when the url of a target changes
27        /// </summary>
28        public event EventHandler<TargetChangedArgs> TargetChanged;
29
30        /// <summary>
31        /// Raised when a target is created, for example when a new page is opened by <c>window.open</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/Window/open"/> or <see cref="NewPageAsync"/>.
32        /// </summary>
33        public event EventHandler<TargetChangedArgs> TargetCreated;
34
35        /// <summary>
36        /// Raised when a target is destroyed, for example when a page is closed
37        /// </summary>
38        public event EventHandler<TargetChangedArgs> TargetDestroyed;
39
40        /// <summary>
41        /// Returns whether BrowserContext is incognito
42        /// The default browser context is the only non-incognito browser context
43        /// </summary>
44        /// <remarks>
45        /// The default browser context cannot be closed
46        /// </remarks>
47        public bool IsIncognito => _id != null;
48
49        /// <summary>
50        /// Gets the browser this browser context belongs to
51        /// </summary>
52        public Browser Browser { get; }
53
54        /// <summary>
55        /// Gets an array of all active targets inside the browser context.
56        /// </summary>
57        /// <returns>An array of all active targets inside the browser context</returns>
58        public Target[] Targets() => Array.FindAll(Browser.Targets(), target => target.BrowserContext == this);
59
60        /// <summary>
61        /// This searches for a target in this specific browser context.
62        /// <example>
63        /// <code>
64        /// <![CDATA[
65        /// await page.EvaluateAsync("() => window.open('https://www.example.com/')");
66        /// var newWindowTarget = await browserContext.WaitForTargetAsync((target) => target.Url == "https://www.example.com/");
67        /// ]]>
68        /// </code>
69        /// </example>
70        /// </summary>
71        /// <param name="predicate">A function to be run for every target</param>
72        /// <param name="options">options</param>
73        /// <returns>Resolves to the first target found that matches the predicate function.</returns>
74        public Task<Target> WaitForTargetAsync(Func<Target, bool> predicate, WaitForOptions options = null)
75            => Browser.WaitForTargetAsync((target) => target.BrowserContext == this && predicate(target), options);
76
77        /// <summary>
78        /// An array of all pages inside the browser context.
79        /// </summary>
80        /// <returns>Task which resolves to an array of all open pages.
81        /// Non visible pages, such as <c>"background_page"</c>, will not be listed here.
82        /// You can find them using <see cref="Target.PageAsync"/>.</returns>
83        public async Task<Page[]> PagesAsync()
84        => (await Task.WhenAll(
85            Targets().Where(t => t.Type == TargetType.Page).Select(t => t.PageAsync())).ConfigureAwait(false))
86            .Where(p => p != null).ToArray();
87
88        /// <summary>
89        /// Creates a new page
90        /// </summary>
91        /// <returns>Task which resolves to a new <see cref="Page"/> object</returns>
92        public Task<Page> NewPageAsync() => Browser.CreatePageInContextAsync(_id);
93
94        /// <summary>
95        /// Closes the browser context. All the targets that belong to the browser context will be closed
96        /// </summary>
97        /// <returns>Task</returns>
98        public Task CloseAsync()
99        {
100            if (_id == null)
101            {
102                throw new PuppeteerException("Non-incognito profiles cannot be closed!");
103            }
104
105            return Browser.DisposeContextAsync(_id);
106        }
107
108        /// <summary>
109        /// Overrides the browser context permissions.
110        /// </summary>
111        /// <returns>The task.</returns>
112        /// <param name="origin">The origin to grant permissions to, e.g. "https://example.com"</param>
113        /// <param name="permissions">
114        /// An array of permissions to grant. All permissions that are not listed here will be automatically denied.
115        /// </param>
116        /// <example>
117        /// <![CDATA[
118        /// var context = browser.DefaultBrowserContext;
119        /// await context.OverridePermissionsAsync("https://html5demos.com", new List<string> {"geolocation"});
120        /// ]]>
121        /// </example>
122        /// <seealso href="https://developer.mozilla.org/en-US/docs/Glossary/Origin"/>
123        public Task OverridePermissionsAsync(string origin, IEnumerable<OverridePermission> permissions)
124            => _connection.SendAsync("Browser.grantPermissions", new BrowserGrantPermissionsRequest
125            {
126                Origin = origin,
127                BrowserContextId = _id,
128                Permissions = permissions.ToArray()
129            });
130
131        /// <summary>
132        /// Clears all permission overrides for the browser context.
133        /// </summary>
134        /// <returns>The task.</returns>
135        public Task ClearPermissionOverridesAsync()
136            => _connection.SendAsync("Browser.resetPermissions", new BrowserResetPermissionsRequest
137            {
138                BrowserContextId = _id
139            });
140
141        internal void OnTargetCreated(Browser browser, TargetChangedArgs args) => TargetCreated?.Invoke(browser, args);
142
143        internal void OnTargetDestroyed(Browser browser, TargetChangedArgs args) => TargetDestroyed?.Invoke(browser, args);
144
145        internal void OnTargetChanged(Browser browser, TargetChangedArgs args) => TargetChanged?.Invoke(browser, args);
146    }
147}
148
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 TargetChangedArgs

    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)