How to use Frame class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

Methods.cs

Source: Methods.cs Github

copy
1using Yove.Proxy;
2using PuppeteerExtraSharp;
3using PuppeteerExtraSharp.Plugins.ExtraStealth;
4using PuppeteerSharp;
5using RuriLib.Attributes;
6using RuriLib.Logging;
7using RuriLib.Models.Bots;
8using System;
9using System.Collections.Generic;
10using System.Linq;
11using System.Threading.Tasks;
12
13using ProxyType = RuriLib.Models.Proxies.ProxyType;
14using RuriLib.Helpers;
15
16namespace RuriLib.Blocks.Puppeteer.Browser
17{
18    [BlockCategory("Browser", "Blocks for interacting with a puppeteer browser", "#e9967a")]
19    public static class Methods
20    {
21        [Block("Opens a new puppeteer browser", name = "Open Browser")]
22        public static async Task PuppeteerOpenBrowser(BotData data, string extraCmdLineArgs = "")
23        {
24            data.Logger.LogHeader();
25
26            // Check if there is already an open browser
27            var oldBrowser = data.TryGetObject<PuppeteerSharp.Browser>("puppeteer");
28            if (oldBrowser is not null && !oldBrowser.IsClosed)
29            {
30                data.Logger.Log("The browser is already open, close it if you want to open a new browser", LogColors.DarkSalmon);
31                return;
32            }
33
34            var args = data.ConfigSettings.BrowserSettings.CommandLineArgs;
35
36            // Extra command line args (to have dynamic args via variables)
37            if (!string.IsNullOrWhiteSpace(extraCmdLineArgs))
38            {
39                args += ' ' + extraCmdLineArgs;
40            }
41
42            // If it's running in docker, currently it runs under root, so add the --no-sandbox otherwise chrome won't work
43            if (Utils.IsDocker())
44            {
45                args += " --no-sandbox";
46            }
47
48            if (data.Proxy != null && data.UseProxy)
49            {
50                if (data.Proxy.Type == ProxyType.Http || !data.Proxy.NeedsAuthentication)
51                {
52                    args += $" --proxy-server={data.Proxy.Type.ToString().ToLower()}://{data.Proxy.Host}:{data.Proxy.Port}";
53                }
54                else
55                {
56                    var proxyType = data.Proxy.Type == ProxyType.Socks5 ? Yove.Proxy.ProxyType.Socks5 : Yove.Proxy.ProxyType.Socks4;
57                    var proxyClient = new ProxyClient(
58                        data.Proxy.Host, data.Proxy.Port,
59                        data.Proxy.Username, data.Proxy.Password, 
60                        proxyType);
61                    data.SetObject("puppeteer.yoveproxy", proxyClient);
62                    args += $" --proxy-server={proxyClient.GetProxy(null).Authority}";
63                }
64            }
65
66            // Configure the options
67            var launchOptions = new LaunchOptions
68            {
69                Args = new string[] { args },
70                ExecutablePath = data.Providers.PuppeteerBrowser.ChromeBinaryLocation,
71                IgnoredDefaultArgs = new string[] { "--disable-extensions", "--enable-automation" },
72                Headless = data.ConfigSettings.BrowserSettings.Headless,
73                DefaultViewport = null // This is important
74            };
75
76            // Add the plugins
77            var extra = new PuppeteerExtra();
78            extra.Use(new StealthPlugin());
79
80            // Launch the browser
81            var browser = await extra.LaunchAsync(launchOptions);
82            browser.IgnoreHTTPSErrors = data.ConfigSettings.BrowserSettings.IgnoreHttpsErrors;
83
84            // Save the browser for further use
85            data.SetObject("puppeteer", browser);
86            var page = (await browser.PagesAsync()).First();
87            SetPageAndFrame(data, page);
88            await SetPageLoadingOptions(data, page);
89
90            // Authenticate if the proxy requires auth
91            if (data.UseProxy && data.Proxy is { NeedsAuthentication: true, Type: ProxyType.Http } proxy)
92                await page.AuthenticateAsync(new Credentials { Username = proxy.Username, Password = proxy.Password });
93
94            data.Logger.Log($"{(launchOptions.Headless ? "Headless " : "")}Browser opened successfully!", LogColors.DarkSalmon);
95        }
96
97        [Block("Closes an open puppeteer browser", name = "Close Browser")]
98        public static async Task PuppeteerCloseBrowser(BotData data)
99        {
100            data.Logger.LogHeader();
101
102            var browser = GetBrowser(data);
103            await browser.CloseAsync();
104            StopYoveProxyInternalServer(data);
105            data.Logger.Log("Browser closed successfully!", LogColors.DarkSalmon);
106        }
107
108        [Block("Opens a new page in a new browser tab", name = "New Tab")]
109        public static async Task PuppeteerNewTab(BotData data)
110        {
111            data.Logger.LogHeader();
112
113            var browser = GetBrowser(data);
114            var page = await browser.NewPageAsync();
115            await SetPageLoadingOptions(data, page);
116
117            SetPageAndFrame(data, page); // Set the new page as active
118            data.Logger.Log($"Opened a new page", LogColors.DarkSalmon);
119        }
120
121        [Block("Closes the currently active browser tab", name = "Close Tab")]
122        public static async Task PuppeteerCloseTab(BotData data)
123        {
124            data.Logger.LogHeader();
125
126            var browser = GetBrowser(data);
127            var page = GetPage(data);
128            
129            // Close the page
130            await page.CloseAsync();
131            
132            // Set the first page as active
133            page = (await browser.PagesAsync()).FirstOrDefault();
134            SetPageAndFrame(data, page);
135
136            if (page != null)
137                await page.BringToFrontAsync();
138
139            data.Logger.Log($"Closed the active page", LogColors.DarkSalmon);
140        }
141
142        [Block("Switches to the browser tab with a specified index", name = "Switch to Tab")]
143        public static async Task PuppeteerSwitchToTab(BotData data, int index)
144        {
145            data.Logger.LogHeader();
146
147            var browser = GetBrowser(data);
148            var page = (await browser.PagesAsync())[index];
149            await page.BringToFrontAsync();
150            SetPageAndFrame(data, page);
151
152            data.Logger.Log($"Switched to tab with index {index}", LogColors.DarkSalmon);
153        }
154
155        [Block("Reloads the current page", name = "Reload")]
156        public static async Task PuppeteerReload(BotData data)
157        {
158            data.Logger.LogHeader();
159
160            var page = GetPage(data);
161            await page.ReloadAsync();
162            SwitchToMainFramePrivate(data);
163
164            data.Logger.Log($"Reloaded the page", LogColors.DarkSalmon);
165        }
166
167        [Block("Goes back to the previously visited page", name = "Go Back")]
168        public static async Task PuppeteerGoBack(BotData data)
169        {
170            data.Logger.LogHeader();
171
172            var page = GetPage(data);
173            await page.GoBackAsync();
174            SwitchToMainFramePrivate(data);
175
176            data.Logger.Log($"Went back to the previously visited page", LogColors.DarkSalmon);
177        }
178
179        [Block("Goes forward to the next visited page", name = "Go Forward")]
180        public static async Task PuppeteerGoForward(BotData data)
181        {
182            data.Logger.LogHeader();
183
184            var page = GetPage(data);
185            await page.GoForwardAsync();
186            SwitchToMainFramePrivate(data);
187
188            data.Logger.Log($"Went forward to the next visited page", LogColors.DarkSalmon);
189        }
190
191        private static PuppeteerSharp.Browser GetBrowser(BotData data)
192            => data.TryGetObject<PuppeteerSharp.Browser>("puppeteer") ?? throw new Exception("The browser is not open!");
193
194        private static PuppeteerSharp.Page GetPage(BotData data)
195            => data.TryGetObject<PuppeteerSharp.Page>("puppeteerPage") ?? throw new Exception("No pages open!");
196
197        private static void SwitchToMainFramePrivate(BotData data)
198            => data.SetObject("puppeteerFrame", GetPage(data).MainFrame);
199
200        private static void SetPageAndFrame(BotData data, PuppeteerSharp.Page page)
201        {
202            data.SetObject("puppeteerPage", page, false);
203            SwitchToMainFramePrivate(data);
204        }
205
206        private static void StopYoveProxyInternalServer(BotData data)
207            => data.TryGetObject<ProxyClient>("puppeteer.yoveproxy")?.Dispose();
208
209        private static async Task SetPageLoadingOptions(BotData data, PuppeteerSharp.Page page)
210        {
211            await page.SetRequestInterceptionAsync(true);
212            page.Request += (sender, e) =>
213            {
214                // If we only want documents and scripts but the resource is not one of those, block
215                if (data.ConfigSettings.BrowserSettings.LoadOnlyDocumentAndScript && 
216                    e.Request.ResourceType != ResourceType.Document && e.Request.ResourceType != ResourceType.Script)
217                {
218                    e.Request.AbortAsync();
219                }
220
221                // If the url contains one of the blocked urls
222                else if (data.ConfigSettings.BrowserSettings.BlockedUrls
223                    .Where(u => !string.IsNullOrWhiteSpace(u))
224                    .Any(u => e.Request.Url.Contains(u, StringComparison.OrdinalIgnoreCase)))
225                {
226                    e.Request.AbortAsync();
227                }
228
229                // Otherwise all good, continue
230                else
231                {
232                    e.Request.ContinueAsync();
233                }
234            };
235
236            if (data.ConfigSettings.BrowserSettings.DismissDialogs)
237            {
238                page.Dialog += (sender, e) =>
239                {
240                    data.Logger.Log($"Dialog automatically dismissed: {e.Dialog.Message}", LogColors.DarkSalmon);
241                    e.Dialog.Dismiss();
242                };
243            }
244        }
245    }
246}
247
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
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)