How to use ExecutionContext class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.ExecutionContext

FrameManager.cs

Source:FrameManager.cs Github

copy

Full Screen

...10    internal class FrameManager11    {12        private readonly CDPSession _client;13        private readonly Page _page;14        private Dictionary<int, ExecutionContext> _contextIdToContext;15        private readonly ILogger _logger;16        internal FrameManager(CDPSession client, FrameTree frameTree, Page page)17        {18            _client = client;19            _page = page;20            Frames = new Dictionary<string, Frame>();21            _contextIdToContext = new Dictionary<int, ExecutionContext>();22            _logger = _client.Connection.LoggerFactory.CreateLogger<FrameManager>();23            _client.MessageReceived += _client_MessageReceived;24            HandleFrameTree(frameTree);25        }26        #region Properties27        internal event EventHandler<FrameEventArgs> FrameAttached;28        internal event EventHandler<FrameEventArgs> FrameDetached;29        internal event EventHandler<FrameEventArgs> FrameNavigated;30        internal event EventHandler<FrameEventArgs> LifecycleEvent;31        internal Dictionary<string, Frame> Frames { get; set; }32        internal Frame MainFrame { get; set; }33        #endregion34        #region Private Methods35        void _client_MessageReceived(object sender, PuppeteerSharp.MessageEventArgs e)36        {37            switch (e.MessageID)38            {39                case "Page.frameAttached":40                    OnFrameAttached(e.MessageData.frameId.ToString(), e.MessageData.parentFrameId.ToString());41                    break;42                case "Page.frameNavigated":43                    OnFrameNavigated(((JObject)e.MessageData.frame).ToObject<FramePayload>());44                    break;45                case "Page.frameDetached":46                    OnFrameDetached(e.MessageData.frameId.ToString());47                    break;48                case "Runtime.executionContextCreated":49                    OnExecutionContextCreated(new ContextPayload(e.MessageData.context));50                    break;51                case "Runtime.executionContextDestroyed":52                    OnExecutionContextDestroyed((int)e.MessageData.executionContextId);53                    break;54                case "Runtime.executionContextsCleared":55                    OnExecutionContextsCleared();56                    break;57                case "Page.lifecycleEvent":58                    OnLifeCycleEvent(e);59                    break;60                default:61                    break;62            }63        }64        private void OnLifeCycleEvent(MessageEventArgs e)65        {66            if (Frames.ContainsKey(e.MessageData.frameId.ToString()))67            {68                Frame frame = Frames[e.MessageData.frameId.ToString()];69                frame.OnLifecycleEvent(e.MessageData.loaderId.ToString(), e.MessageData.name.ToString());70                LifecycleEvent?.Invoke(this, new FrameEventArgs(frame));71            }72        }73        private void OnExecutionContextsCleared()74        {75            foreach (var context in _contextIdToContext.Values)76            {77                RemoveContext(context);78            }79            _contextIdToContext.Clear();80        }81        private void OnExecutionContextDestroyed(int executionContextId)82        {83            _contextIdToContext.TryGetValue(executionContextId, out var context);84            if (context != null)85            {86                _contextIdToContext.Remove(executionContextId);87                RemoveContext(context);88            }89        }90        public JSHandle CreateJsHandle(int contextId, dynamic remoteObject)91        {92            _contextIdToContext.TryGetValue(contextId, out var storedContext);93            if (storedContext == null)94            {95                _logger.LogError("INTERNAL ERROR: missing context with id = {ContextId}", contextId);96            }97            if (remoteObject.subtype == "node")98            {99                return new ElementHandle(storedContext, _client, remoteObject, _page);100            }101            return new JSHandle(storedContext, _client, remoteObject);102        }103        private void OnExecutionContextCreated(ContextPayload contextPayload)104        {105            var context = new ExecutionContext(_client, contextPayload,106                remoteObject => CreateJsHandle(contextPayload.Id, remoteObject));107            _contextIdToContext[contextPayload.Id] = context;108            var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;109            if (frame != null && context.IsDefault)110            {111                frame.SetDefaultContext(context);112            }113        }114        private void OnFrameDetached(string frameId)115        {116            if (Frames.ContainsKey(frameId))117            {118                RemoveFramesRecursively(Frames[frameId]);119            }120        }121        private void OnFrameNavigated(FramePayload framePayload)122        {123            var isMainFrame = string.IsNullOrEmpty(framePayload.ParentId);124            var frame = isMainFrame ? MainFrame : Frames[framePayload.Id];125            Contract.Assert(isMainFrame || frame != null, "We either navigate top level or have old version of the navigated frame");126            // Detach all child frames first.127            if (frame != null)128            {129                while (frame.ChildFrames.Count > 0)130                {131                    RemoveFramesRecursively(frame.ChildFrames[0]);132                }133            }134            // Update or create main frame.135            if (isMainFrame)136            {137                if (frame != null)138                {139                    // Update frame id to retain frame identity on cross-process navigation.140                    if (frame.Id != null)141                    {142                        Frames.Remove(frame.Id);143                    }144                    frame.Id = framePayload.Id;145                }146                else147                {148                    // Initial main frame navigation.149                    frame = new Frame(this._client, this._page, null, framePayload.Id);150                }151                Frames[framePayload.Id] = frame;152                MainFrame = frame;153            }154            // Update frame payload.155            frame.Navigated(framePayload);156            FrameNavigated?.Invoke(this, new FrameEventArgs(frame));157        }158        private void RemoveContext(ExecutionContext context)159        {160            var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;161            if (frame != null && context.IsDefault)162            {163                frame.SetDefaultContext(null);164            }165        }166        private void RemoveFramesRecursively(Frame frame)167        {168            while (frame.ChildFrames.Count > 0)169            {170                RemoveFramesRecursively(frame.ChildFrames[0]);171            }172            frame.Detach();...

Full Screen

Full Screen

JSHandle.cs

Source:JSHandle.cs Github

copy

Full Screen

...10    /// JSHandle represents an in-page JavaScript object. JSHandles can be created with the <see cref="Page.EvaluateExpressionHandleAsync(string)"/> and <see cref="Page.EvaluateFunctionHandleAsync(string, object[])"/> methods.11    /// </summary>12    public class JSHandle13    {14        internal JSHandle(ExecutionContext context, CDPSession client, JToken remoteObject)15        {16            ExecutionContext = context;17            Client = client;18            Logger = Client.Connection.LoggerFactory.CreateLogger(GetType());19            RemoteObject = remoteObject;20        }21        /// <summary>22        /// Gets the execution context.23        /// </summary>24        /// <value>The execution context.</value>25        public ExecutionContext ExecutionContext { get; }26        /// <summary>27        /// Gets or sets a value indicating whether this <see cref="JSHandle"/> is disposed.28        /// </summary>29        /// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value>30        public bool Disposed { get; private set; }31        /// <summary>32        /// Gets or sets the remote object.33        /// </summary>34        /// <value>The remote object.</value>35        public JToken RemoteObject { get; }36        /// <summary>37        /// Gets the client.38        /// </summary>39        /// <value>The client.</value>40        protected CDPSession Client { get; }41        /// <summary>42        /// Gets the logger.43        /// </summary>44        /// <value>The logger.</value>45        protected ILogger Logger { get; }46        /// <summary>47        /// Fetches a single property from the referenced object48        /// </summary>49        /// <param name="propertyName">property to get</param>50        /// <returns>Task of <see cref="JSHandle"/></returns>51        public async Task<JSHandle> GetPropertyAsync(string propertyName)52        {53            var objectHandle = await ExecutionContext.EvaluateFunctionHandleAsync(@"(object, propertyName) => {54              const result = { __proto__: null};55              result[propertyName] = object[propertyName];56              return result;57            }", this, propertyName).ConfigureAwait(false);58            var properties = await objectHandle.GetPropertiesAsync().ConfigureAwait(false);59            properties.TryGetValue(propertyName, out var result);60            await objectHandle.DisposeAsync().ConfigureAwait(false);61            return result;62        }63        /// <summary>64        /// Returns a <see cref="Dictionary{TKey, TValue}"/> with property names as keys and <see cref="JSHandle"/> instances for the property values.65        /// </summary>66        /// <returns>Task which resolves to a <see cref="Dictionary{TKey, TValue}"/></returns>67        /// <example>68        /// <code>69        /// var handle = await page.EvaluateExpressionHandle("({window, document})");70        /// var properties = await handle.GetPropertiesAsync();71        /// var windowHandle = properties["window"];72        /// var documentHandle = properties["document"];73        /// await handle.DisposeAsync();74        /// </code>75        /// </example>76        public async Task<Dictionary<string, JSHandle>> GetPropertiesAsync()77        {78            var response = await Client.SendAsync("Runtime.getProperties", new79            {80                objectId = RemoteObject[MessageKeys.ObjectId].AsString(),81                ownProperties = true82            }).ConfigureAwait(false);83            var result = new Dictionary<string, JSHandle>();84            foreach (var property in response[MessageKeys.Result])85            {86                if (property[MessageKeys.Enumerable] == null)87                {88                    continue;89                }90                result.Add(property[MessageKeys.Name].AsString(), ExecutionContext.CreateJSHandle(property[MessageKeys.Value]));91            }92            return result;93        }94        /// <summary>95        /// Returns a JSON representation of the object96        /// </summary>97        /// <returns>Task</returns>98        /// <remarks>99        /// The method will return an empty JSON if the referenced object is not stringifiable. It will throw an error if the object has circular references100        /// </remarks>101        public async Task<object> JsonValueAsync() => await JsonValueAsync<object>().ConfigureAwait(false);102        /// <summary>103        /// Returns a JSON representation of the object104        /// </summary>105        /// <typeparam name="T">A strongly typed object to parse to</typeparam>106        /// <returns>Task</returns>107        /// <remarks>108        /// The method will return an empty JSON if the referenced object is not stringifiable. It will throw an error if the object has circular references109        /// </remarks>110        public async Task<T> JsonValueAsync<T>()111        {112            var objectId = RemoteObject[MessageKeys.ObjectId];113            if (objectId != null)114            {115                var response = await Client.SendAsync("Runtime.callFunctionOn", new Dictionary<string, object>116                {117                    ["functionDeclaration"] = "function() { return this; }",118                    [MessageKeys.ObjectId] = objectId,119                    ["returnByValue"] = true,120                    ["awaitPromise"] = true121                }).ConfigureAwait(false);122                return (T)RemoteObjectHelper.ValueFromRemoteObject<T>(response[MessageKeys.Result]);123            }124            return (T)RemoteObjectHelper.ValueFromRemoteObject<T>(RemoteObject);125        }126        /// <summary>127        /// Disposes the Handle. It will mark the JSHandle as disposed and release the <see cref="JSHandle.RemoteObject"/>128        /// </summary>129        /// <returns>The async.</returns>130        public async Task DisposeAsync()131        {132            if (Disposed)133            {134                return;135            }136            Disposed = true;137            await RemoteObjectHelper.ReleaseObject(Client, RemoteObject, Logger).ConfigureAwait(false);138        }139        /// <inheritdoc/>140        public override string ToString()141        {142            if ((RemoteObject)[MessageKeys.ObjectId] != null)143            {144                var type = RemoteObject[MessageKeys.Subtype] ?? RemoteObject[MessageKeys.Type];145                return "JSHandle@" + type;146            }147            return "JSHandle:" + RemoteObjectHelper.ValueFromRemoteObject<object>(RemoteObject)?.ToString();148        }149        internal object FormatArgument(ExecutionContext context)150        {151            if (ExecutionContext != context)152            {153                throw new PuppeteerException("JSHandles can be evaluated only in the context they were created!");154            }155            if (Disposed)156            {157                throw new PuppeteerException("JSHandle is disposed!");158            }159            var unserializableValue = RemoteObject[MessageKeys.UnserializableValue];160            if (unserializableValue != null)161            {162                return unserializableValue;163            }164            if (RemoteObject[MessageKeys.ObjectId] == null)165            {...

Full Screen

Full Screen

Worker.cs

Source:Worker.cs Github

copy

Full Screen

...22    /// </example>23    public class Worker24    {25        private readonly CDPSession _client;26        private ExecutionContext _executionContext;27        // private readonly Func<ConsoleType, JSHandle[], StackTrace, Task> _consoleAPICalled;28        private readonly Action<EvaluateExceptionResponseDetails> _exceptionThrown;29        private readonly TaskCompletionSource<ExecutionContext> _executionContextCallback;30        private Func<ExecutionContext, RemoteObject, JSHandle> _jsHandleFactory;31        internal Worker(32            CDPSession client,33            string url,34            Func<ConsoleType, JSHandle[], Task> consoleAPICalled,35            Action<EvaluateExceptionResponseDetails> exceptionThrown)36        {37            _client = client;38            Url = url;39            _exceptionThrown = exceptionThrown;40            _client.MessageReceived += OnMessageReceived;41            _executionContextCallback = new TaskCompletionSource<ExecutionContext>(TaskCreationOptions.RunContinuationsAsynchronously);42            _ = _client.SendAsync("Runtime.enable").ContinueWith(task =>43            {44            });45            _ = _client.SendAsync("Log.enable").ContinueWith(task =>46            {47            });48        }49        /// <summary>50        /// Gets the Worker URL.51        /// </summary>52        /// <value>Worker URL.</value>53        public string Url { get; }54        internal void OnMessageReceived(object sender, MessageEventArgs e)55        {56            try57            {58                switch (e.MessageID)59                {60                    case "Runtime.executionContextCreated":61                        OnExecutionContextCreated(e.MessageData.ToObject<RuntimeExecutionContextCreatedResponse>(true));62                        break;63                    //case "Runtime.consoleAPICalled":64                    //    await OnConsoleAPICalled(e).ConfigureAwait(false);65                    //    break;66                    case "Runtime.exceptionThrown":67                        OnExceptionThrown(e.MessageData.ToObject<RuntimeExceptionThrownResponse>(true));68                        break;69                }70            }71            catch (Exception ex)72            {73                var message = $"Worker failed to process {e.MessageID}. {ex.Message}. {ex.StackTrace}";74                _client.Close(message);75            }76        }77        private void OnExceptionThrown(RuntimeExceptionThrownResponse e) => _exceptionThrown(e.ExceptionDetails);78        private void OnExecutionContextCreated(RuntimeExecutionContextCreatedResponse e)79        {80            if (_jsHandleFactory == null)81            {82                _jsHandleFactory = (ctx, remoteObject) => new JSHandle(ctx, _client, remoteObject);83                _executionContext = new ExecutionContext(84                    _client,85                    e.Context,86                    null);87                _executionContextCallback.TrySetResult(_executionContext);88            }89        }90    }91}...

Full Screen

Full Screen

QueryObjectsTests.cs

Source:QueryObjectsTests.cs Github

copy

Full Screen

...10    {11        public QueryObjectsTests(ITestOutputHelper output) : base(output)12        {13        }14        [PuppeteerTest("page.spec.ts", "ExecutionContext.queryObjects", "should work")]15        [SkipBrowserFact(skipFirefox: true)]16        public async Task ShouldWork()17        {18            // Instantiate an object19            await Page.EvaluateExpressionAsync("window.set = new Set(['hello', 'world'])");20            var prototypeHandle = await Page.EvaluateExpressionHandleAsync("Set.prototype");21            var objectsHandle = await Page.QueryObjectsAsync(prototypeHandle);22            var count = await Page.EvaluateFunctionAsync<int>("objects => objects.length", objectsHandle);23            Assert.Equal(1, count);24            var values = await Page.EvaluateFunctionAsync<string[]>("objects => Array.from(objects[0].values())", objectsHandle);25            Assert.Equal(new[] { "hello", "world" }, values);26        }27        [PuppeteerTest("page.spec.ts", "ExecutionContext.queryObjects", "should work for non-blank page")]28        [SkipBrowserFact(skipFirefox: true)]29        public async Task ShouldWorkForNonBlankPage()30        {31            // Instantiate an object32            await Page.GoToAsync(TestConstants.EmptyPage);33            await Page.EvaluateFunctionAsync("() => window.set = new Set(['hello', 'world'])");34            var prototypeHandle = await Page.EvaluateFunctionHandleAsync("() => Set.prototype");35            var objectsHandle = await Page.QueryObjectsAsync(prototypeHandle);36            var count = await Page.EvaluateFunctionAsync<int>("objects => objects.length", objectsHandle);37            Assert.Equal(1, count);38        }39        [PuppeteerTest("page.spec.ts", "ExecutionContext.queryObjects", "should fail for disposed handles")]40        [PuppeteerFact]41        public async Task ShouldFailForDisposedHandles()42        {43            var prototypeHandle = await Page.EvaluateExpressionHandleAsync("HTMLBodyElement.prototype");44            await prototypeHandle.DisposeAsync();45            var exception = await Assert.ThrowsAsync<PuppeteerException>(()46                => Page.QueryObjectsAsync(prototypeHandle));47            Assert.Equal("Prototype JSHandle is disposed!", exception.Message);48        }49        [PuppeteerTest("page.spec.ts", "ExecutionContext.queryObjects", "should fail primitive values as prototypes")]50        [PuppeteerFact]51        public async Task ShouldFailPrimitiveValuesAsPrototypes()52        {53            var prototypeHandle = await Page.EvaluateExpressionHandleAsync("42");54            var exception = await Assert.ThrowsAsync<PuppeteerException>(()55                => Page.QueryObjectsAsync(prototypeHandle));56            Assert.Equal("Prototype JSHandle must not be referencing primitive value", exception.Message);57        }58    }59}...

Full Screen

Full Screen

TakeScreenshot.cs

Source:TakeScreenshot.cs Github

copy

Full Screen

...13        [FunctionName("TakeScreenshot")]14        public static async Task<IActionResult> Run(15            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req, 16            TraceWriter log,17            Microsoft.Azure.WebJobs.ExecutionContext context)18        {19            var config = new ConfigurationBuilder()20                .SetBasePath(context.FunctionAppDirectory)21                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)22                .AddEnvironmentVariables()23                .Build();24            string url = req.Query["url"];25            if (url == null)26            {27                return new BadRequestObjectResult("Please pass a name on the query string");28            }29            else30            {31                string apikey = config["browserlessApiKey"];...

Full Screen

Full Screen

ExecutionContextTests.cs

Source:ExecutionContextTests.cs Github

copy

Full Screen

...5using Xunit.Abstractions;6namespace PuppeteerSharp.Tests.FrameTests7{8    [Collection(TestConstants.TestFixtureCollectionName)]9    public class ExecutionContextTests : PuppeteerPageBaseTest10    {11        public ExecutionContextTests(ITestOutputHelper output) : base(output)12        {13        }14        [PuppeteerTest("frame.spec.ts", "Frame.executionContext", "should work")]15        [PuppeteerFact]16        public async Task ShouldWork()17        {18            await Page.GoToAsync(TestConstants.EmptyPage);19            await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);20            Assert.Equal(2, Page.Frames.Length);21            var context1 = await Page.MainFrame.GetExecutionContextAsync();22            var context2 = await Page.FirstChildFrame().GetExecutionContextAsync();23            Assert.NotNull(context1);24            Assert.NotNull(context2);25            Assert.NotEqual(context1, context2);26            Assert.Equal(Page.MainFrame, context1.Frame);27            Assert.Equal(Page.FirstChildFrame(), context2.Frame);28            await Task.WhenAll(29                context1.EvaluateExpressionAsync("window.a = 1"),30                context2.EvaluateExpressionAsync("window.a = 2")31            );32            var a1 = context1.EvaluateExpressionAsync<int>("window.a");33            var a2 = context2.EvaluateExpressionAsync<int>("window.a");34            await Task.WhenAll(a1, a2);35            Assert.Equal(1, a1.Result);36            Assert.Equal(2, a2.Result);...

Full Screen

Full Screen

SourceUrl.cs

Source:SourceUrl.cs Github

copy

Full Screen

...21                var contextField = mainWord.GetType()22                    .GetField("_contextResolveTaskWrapper", BindingFlags.NonPublic | BindingFlags.Instance);23                if (contextField is not null)24                {25                    var context = (TaskCompletionSource<ExecutionContext>) contextField.GetValue(mainWord);26                    var execution = await context.Task;27                    var suffixField = execution.GetType()28                        .GetField("_evaluationScriptSuffix", BindingFlags.NonPublic | BindingFlags.Instance);29                    suffixField?.SetValue(execution, "//# sourceURL=''");30                }31            };32        }33    }34}...

Full Screen

Full Screen

ElementHandle.cs

Source:ElementHandle.cs Github

copy

Full Screen

...7    /// </summary>8    public class ElementHandle : JSHandle9    {10        internal ElementHandle(11            ExecutionContext context,12            CDPSession client,13            RemoteObject remoteObject)14            : base(context, client, remoteObject) { }15    }16}...

Full Screen

Full Screen

ExecutionContext

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        static void Main(string[] args)7        {8            Console.WriteLine("Hello World!");9        }10        private static async Task Run()11        {

Full Screen

Full Screen

ExecutionContext

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        static async Task Main(string[] args)7        {8            var browser = await Puppeteer.LaunchAsync(new LaunchOptions9            {10            });11            var page = await browser.NewPageAsync();12            await page.WaitForSelectorAsync("input[name=q]");13            await page.TypeAsync("input[name=q]", "puppeteer-sharp", new TypeOptions { Delay = 100 });14            await page.ClickAsync("input[name=q]", new ClickOptions { Delay = 100 });15            await page.WaitForSelectorAsync("div.g");16            var results = await page.QuerySelectorAllAsync("div.g");17            foreach (var result in results)18            {19                var title = await result.QuerySelectorAsync("h3");20                var link = await result.QuerySelectorAsync("a");21                Console.WriteLine($"{await title.EvaluateFunctionAsync<string>("node => node.innerText")} - {await link.EvaluateFunctionAsync<string>("node => node.href")}");22            }23            await browser.CloseAsync();24        }25    }26}27const puppeteer = require('puppeteer');28(async () => {29  const browser = await puppeteer.launch();30  const page = await browser.newPage();31  await page.waitForSelector('input[name="q"]');32  await page.type('input[name="q"]', 'puppeteer-sharp', { delay: 100 });33  await page.click('input[name="q"]', { delay: 100 });34  await page.waitForSelector('div.g

Full Screen

Full Screen

ExecutionContext

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6    {7        static void Main(string[] args)8        {9            MainAsync().Wait();10        }11        static async Task MainAsync()12        {13            var options = new LaunchOptions { Headless = true };14            using (var browser = await Puppeteer.LaunchAsync(options))15            using (var page = await browser.NewPageAsync())16            {17                var content = await page.GetContentAsync();18                File.WriteAllText("content.html", content);19            }20        }21    }22}23using System;24using System.IO;25using System.Threading.Tasks;26using PuppeteerSharp;27{28    {29        static void Main(string[] args)30        {31            MainAsync().Wait();32        }33        static async Task MainAsync()34        {35            var options = new LaunchOptions { Headless = true };36            using (var browser = await Puppeteer.LaunchAsync(options))37            using (var page = await browser.NewPageAsync())38            {39                var content = await page.GetContentAsync();40                File.WriteAllText("content.html", content);41            }42        }43    }44}45using System;46using System.IO;47using System.Threading.Tasks;48using PuppeteerSharp;49{50    {51        static void Main(string[] args)52        {53            MainAsync().Wait();54        }55        static async Task MainAsync()56        {57            var options = new LaunchOptions { Headless = true };58            using (var browser = await Puppeteer.LaunchAsync(options))59            using (var page = await browser.NewPageAsync())60            {61                var content = await page.GetContentAsync();62                File.WriteAllText("content.html", content);63            }64        }65    }66}

Full Screen

Full Screen

ExecutionContext

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.IO;5using System.Text;6using System.Collections.Generic;7using System.Text.RegularExpressions;8{9    {10        static async Task Main(string[] args)11        {12            var browser = await Puppeteer.LaunchAsync(new LaunchOptions13            {14                Args = new string[] { "--start-maximized" }15            });16            var page = await browser.NewPageAsync();17            await page.EvaluateExpressionAsync("document.body.style.backgroundColor = 'red'");18            await Task.Delay(5000);19            await browser.CloseAsync();20        }21    }22}23using System;24using System.Threading.Tasks;25using PuppeteerSharp;26using System.IO;27using System.Text;28using System.Collections.Generic;29using System.Text.RegularExpressions;30{31    {32        static async Task Main(string[] args)33        {34            var browser = await Puppeteer.LaunchAsync(new LaunchOptions35            {36                Args = new string[] { "--start-maximized" }37            });38            var page = await browser.NewPageAsync();39            var element = await page.QuerySelectorAsync("input[title='Search']");40            await element.EvaluateFunctionAsync("element => element.style.backgroundColor = 'red'");41            await Task.Delay(5000);42            await browser.CloseAsync();43        }44    }45}46using System;47using System.Threading.Tasks;48using PuppeteerSharp;49using System.IO;50using System.Text;51using System.Collections.Generic;

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful