How to use LaunchAsync method of PuppeteerSharp.Puppeteer class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Puppeteer.LaunchAsync

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

Program.cs

Source: Program.cs Github

copy
1using System;
2using System.Linq;
3
4namespace web_browser_csharp
5{
6    class Program
7    {
8        static PuppeteerSharp.Browser browser;
9        static PuppeteerSharp.Page browserPage;
10
11        static Action<string> callbackFromBrowserDelegate;
12
13        static string UserDataDirPath() =>
14            System.IO.Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "bot", "web-browser", "user-data");
15
16
17        static void Main(string[] args)
18        {
19            /*
20            2020-02-17 Observation before introducing the killing of previous web browser processes:
21            LaunchAsync failed if a process from the last run was still present.
22            (See report of this issue at https://forum.botengine.org/t/farm-manager-tribal-wars-2-farmbot/3038/32?u=viir)
23
24            Unhandled exception. System.AggregateException: One or more errors occurred. (Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)
25            [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_000
26            [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache
27            [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -2
28            [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process.
29            )
30            ---> PuppeteerSharp.ChromiumProcessException: Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)
31            [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_000
32            [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache
33            [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -2
34            [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process.
35
36            at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p)
37            at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p)
38            at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options)
39            at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options)
40            */
41
42            KillPreviousWebBrowserProcesses();
43
44            StartWebBrowser().Wait();
45        }
46
47        static void KillPreviousWebBrowserProcesses()
48        {
49            var matchingProcesses =
50                System.Diagnostics.Process.GetProcesses()
51                /*
52                2020-02-17
53                .Where(process => process.StartInfo.Arguments.Contains(UserDataDirPath(), StringComparison.InvariantCultureIgnoreCase))
54                */
55                .Where(ProcessIsWebBrowser)
56                .ToList();
57
58            foreach (var process in matchingProcesses)
59            {
60                if (process.HasExited)
61                    continue;
62
63                process.Kill();
64            }
65        }
66
67        static bool ProcessIsWebBrowser(System.Diagnostics.Process process)
68        {
69            try
70            {
71                return process.MainModule.FileName.Contains(".local-chromium");
72            }
73            catch
74            {
75                return false;
76            }
77        }
78
79        static async System.Threading.Tasks.Task StartWebBrowser()
80        {
81            await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);
82            browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions
83            {
84                Headless = false,
85                UserDataDir = UserDataDirPath(),
86                DefaultViewport = null,
87            });
88            browserPage = (await browser.PagesAsync()).FirstOrDefault() ?? await browser.NewPageAsync();
89
90            await browserPage.ExposeFunctionAsync("____callback____", (string returnValue) =>
91            {
92                callbackFromBrowserDelegate?.Invoke(returnValue);
93                return 0;
94            });
95        }
96
97    }
98}
99
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 LaunchAsync code on LambdaTest Cloud Grid

Execute automation tests with LaunchAsync 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)