How to use CloseAsync method of PuppeteerSharp.Page class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.CloseAsync

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

test vueJS.csx

Source: test vueJS.csx Github

copy
1#! "netcoreapp2.0"
2
3#load "../../module/chrome/PuppeteerUtility.csx"
4
5using PuppeteerSharp;
6
7var (page, browser) = await PuppeteerUtility.GetPage();
8
9// found this example here: http://www.hardkoded.com/blog/creating-whatsapp-bot-puppteer-sharp
10// documentation is here: https://www.puppeteersharp.com/api/PuppeteerSharp.Page.html
11await page.ExposeFunctionAsync("funcTest1", ()=>{
12    Console.WriteLine($"Function Test 1 Called");
13});
14
15
16/*
17See vue.js documentation here:
18https://vuejs.org/v2/guide/instance.html
19
20*/
21
22await page.SetContentAsync(html: @"
23    <div id='displayDiv'>
24        {{title}}
25        <br />You've cliicked the button {{counter}} times.
26        <br /><button type='button' v-on:click='onButton1Click'>Click Me!</button>
27        <br /><button type='button' v-on:click='quit'>Quit</button>
28    </div>
29
30    <script type='module'>
31    import Vue from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'
32
33    let vm = new Vue({
34        el: '#displayDiv',
35        data:  {
36            title: 'Hello World!',
37            counter: 0
38        },
39        methods: {
40            onButton1Click: () => {
41                console.log('Button was clicked');
42                vm.counter++;
43                console.log(vm);
44                console.log('Preparing to call funcTest1');
45                console.log(funcTest1);
46                funcTest1().then(() => {
47                    console.log('Success');
48                }, (err)=>{
49                    console.error('Something went wrong...');
50                });
51                console.log('funcTest1 should have been called');
52            },
53            quit: () => {
54                window.programDone = true;
55            }
56        }
57    })
58    </script>
59");
60
61
62
63async Task waitForProgramEnd(){
64    /*
65    This stuff keeps the browser open until our program is done.
66    */
67    await page.EvaluateFunctionAsync(@"
68        ()=> {
69            window.programDone = false;
70        }
71    ");
72
73    await page.WaitForExpressionAsync("window.programDone === true", new WaitForFunctionOptions{
74        Timeout = 0 // disable timeout
75    });
76    Console.WriteLine("Program finished triggered");
77    // program is done so close everything out
78    await page.CloseAsync();
79    await browser.CloseAsync();
80}
81
82
83await waitForProgramEnd();
84
85
Full Screen

test vueJS - Example1 - Refresh Top System Processes.csx

Source: test vueJS - Example1 - Refresh Top System Processes.csx Github

copy
1#load "../../module/chrome/PuppeteerUtility.csx"
2
3using PuppeteerSharp;
4
5var (page, browser) = await PuppeteerUtility.GetPage();
6
7
8public class ProcessInfo{
9    public string Name {get; set; }
10}
11
12// found this example here: http://www.hardkoded.com/blog/creating-whatsapp-bot-puppteer-sharp
13// documentation is here: https://www.puppeteersharp.com/api/PuppeteerSharp.Page.html
14await page.ExposeFunctionAsync("sysCallGetTopProcesses", ()=>{
15    var processes = Process.GetProcesses().Where(p=>{
16        try{
17            string name = p.ProcessName;
18            var useTime = p.UserProcessorTime;
19            return true;
20        }catch(Exception ex){return false;}
21    }).OrderBy(p=>p.UserProcessorTime.Ticks).Take(10);
22    Console.WriteLine($"Found: {processes.Count()}");
23
24    var result = processes.Select(p=> new ProcessInfo{
25        Name = p.ProcessName
26    }).ToList();
27
28    return Newtonsoft.Json.Linq.JArray.FromObject(result);
29});
30
31
32/*
33See vue.js documentation here:
34https://vuejs.org/v2/guide/instance.html
35
36*/
37
38await page.SetContentAsync(html: @"
39    <div id='displayDiv'>
40        {{title}}
41        <table>
42            <thead>
43                <tr>
44                    <th>Process Name</th>
45                </tr>
46            </thead>
47            <tbody>
48                <tr v-for='p in processes'>
49                    <td>{{p.Name}}</td>
50                </tr>
51            </tbody>
52        </table>
53        <br /><button type='button' v-on:click='refreshProcesses'>Refresh</button>
54        <br /><button type='button' v-on:click='quit'>Quit</button>
55    </div>
56
57    <script type='module'>
58    import Vue from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'
59
60    let vm = new Vue({
61        el: '#displayDiv',
62        data:  {
63            title: 'System Processes Display',
64            processes: []
65        },
66        methods: {
67            refreshProcesses: () => {
68
69                sysCallGetTopProcesses().then((processes)=>{
70                    console.log(processes);
71                    vm.processes.splice(0, vm.processes.length);
72                    for(let p of processes){
73                        vm.processes.push(p);
74                    }
75                }, (err)=>{
76
77                });
78
79            },
80            quit: () => {
81                window.programDone = true;
82            }
83        }
84    })
85    </script>
86");
87
88
89
90async Task waitForProgramEnd(){
91    /*
92    This stuff keeps the browser open until our program is done.
93    */
94    await page.EvaluateFunctionAsync(@"
95        ()=> {
96            window.programDone = false;
97        }
98    ");
99
100    await page.WaitForExpressionAsync("window.programDone === true", new WaitForFunctionOptions{
101        Timeout = 0 // disable the timeout
102    });
103    Console.WriteLine("Program finished triggered");
104    // program is done so close everything out
105    await page.CloseAsync();
106    await browser.CloseAsync();
107}
108
109
110await waitForProgramEnd();
111
112
Full Screen

PuppeteerBrowser.cs

Source: PuppeteerBrowser.cs Github

copy
1using PuppeteerSharp;
2using System;
3
4namespace HlidacStatu.Util.WebShot
5{
6    public class PuppeteerBrowser : IDisposable
7    {
8
9        static PuppeteerBrowser()
10        {
11            new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision).Wait();
12        }
13        public static Devmasters.Core.Logging.Logger logger = new Devmasters.Core.Logging.Logger("HlidacStatu.Util.Webshots");
14
15        private static readonly PuppeteerBrowser theOnlyInstance = new PuppeteerBrowser("theOnlyInstance");
16
17        public static PuppeteerBrowser TheOnlyStaticInstance
18        {
19            get
20            {
21                return theOnlyInstance;
22            }
23        }
24
25        PuppeteerSharp.Browser browser = null;
26        PuppeteerSharp.Page page = null;
27
28        int width = 00;
29        int height = 0;
30        public string Name { get; set; } = null;
31        public PuppeteerBrowser(string name = null)
32            : this(1920, 1080, name)
33        {
34        }
35
36        public PuppeteerBrowser(int displaywidth, int displayheight, string name = null)
37        {
38            this.width = displaywidth;
39            this.height = displayheight;
40            this.Name = "PuppeteerBrowser-" + (name ?? Devmasters.Core.TextUtil.GenRandomString(10));
41            Init();
42        }
43
44        private void Init()
45        {
46            logger.Debug($"{this.Name}: Initiating PuppeteerBrowser");
47            var chromeBinaryFileName = Devmasters.Core.Util.Config.GetConfigValue("ChromeBinaryFullPath");
48
49            var launchOptions = new LaunchOptions()
50            {
51                Headless = true,
52                DefaultViewport = new ViewPortOptions()
53                {
54                    DeviceScaleFactor = 1,
55                    IsLandscape = false,
56                    HasTouch = false,
57                    IsMobile = false,
58                    Height = this.height,
59                    Width = this.width,
60                }
61            };
62            if (!string.IsNullOrEmpty(chromeBinaryFileName))
63                launchOptions.ExecutablePath = chromeBinaryFileName;
64
65
66            this.browser = Puppeteer.LaunchAsync(launchOptions).Result;
67            this.page = browser.NewPageAsync().Result;
68            logger.Info($"{this.Name}: Initiated PuppeteerBrowser");
69
70        }
71
72        object browserLock = new object();
73        public PuppeteerSharp.Page Page()
74        {
75                return this.page;
76        }
77
78        public void WarmUp()
79        {
80            logger.Debug($"{this.Name}: Warming up");
81            this.page.GoToAsync("https://www.google.com").Wait();
82        }
83
84
85        internal void RecreatedChrome()
86        {
87            logger.Info($"{this.Name}: Recreating PuppeteerBrowser");
88            lock (browserLock)
89            {
90                this.page.Dispose();
91                this.browser.CloseAsync().Wait();
92            }
93            System.Threading.Thread.Sleep(500);
94            Init();
95        }
96
97        #region IDisposable Support
98        private bool disposedValue = false; // To detect redundant calls
99
100        protected virtual void Dispose(bool disposing)
101        {
102            logger.Info($"{this.Name}: Disposing PuppeteerBrowser Instance");
103            if (!disposedValue)
104            {
105                if (disposing)
106                {
107                    // TODO: dispose managed state (managed objects).
108                }
109
110                logger.Debug($"{this.Name}: Closing PuppeteerBrowser");
111                this.browser.CloseAsync().Wait();
112                logger.Debug($"{this.Name}: Closed PuppeteerBrowser");
113                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
114                // TODO: set large fields to null.
115
116                disposedValue = true;
117            }
118        }
119
120        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
121        ~PuppeteerBrowser()
122        {
123            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
124            Dispose(false);
125        }
126
127        // This code added to correctly implement the disposable pattern.
128        public void Dispose()
129        {
130            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
131            Dispose(true);
132            // TODO: uncomment the following line if the finalizer is overridden above.
133            GC.SuppressFinalize(this);
134        }
135        #endregion
136
137    }
138}
139
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 method in Page

Trigger CloseAsync code on LambdaTest Cloud Grid

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