How to use OnLifecycleEvent method of PuppeteerSharp.Frame class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.OnLifecycleEvent

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

FrameManager.cs

Source: FrameManager.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Diagnostics.Contracts;
4using PuppeteerSharp.Input;
5using Newtonsoft.Json.Linq;
6using System.Diagnostics;
7using Microsoft.Extensions.Logging;
8
9namespace PuppeteerSharp
10{
11    internal class FrameManager
12    {
13        private readonly CDPSession _client;
14        private readonly Page _page;
15        private Dictionary<int, ExecutionContext> _contextIdToContext;
16        private readonly ILogger _logger;
17
18        internal FrameManager(CDPSession client, FrameTree frameTree, Page page)
19        {
20            _client = client;
21            _page = page;
22            Frames = new Dictionary<string, Frame>();
23            _contextIdToContext = new Dictionary<int, ExecutionContext>();
24            _logger = _client.Connection.LoggerFactory.CreateLogger<FrameManager>();
25
26            _client.MessageReceived += _client_MessageReceived;
27            HandleFrameTree(frameTree);
28        }
29
30        #region Properties
31        internal event EventHandler<FrameEventArgs> FrameAttached;
32        internal event EventHandler<FrameEventArgs> FrameDetached;
33        internal event EventHandler<FrameEventArgs> FrameNavigated;
34        internal event EventHandler<FrameEventArgs> LifecycleEvent;
35
36        internal Dictionary<string, Frame> Frames { get; set; }
37        internal Frame MainFrame { get; set; }
38
39        #endregion
40
41        #region Private Methods
42
43        void _client_MessageReceived(object sender, PuppeteerSharp.MessageEventArgs e)
44        {
45            switch (e.MessageID)
46            {
47                case "Page.frameAttached":
48                    OnFrameAttached(e.MessageData.frameId.ToString(), e.MessageData.parentFrameId.ToString());
49                    break;
50
51                case "Page.frameNavigated":
52                    OnFrameNavigated(((JObject)e.MessageData.frame).ToObject<FramePayload>());
53                    break;
54
55                case "Page.frameDetached":
56                    OnFrameDetached(e.MessageData.frameId.ToString());
57                    break;
58
59                case "Runtime.executionContextCreated":
60                    OnExecutionContextCreated(new ContextPayload(e.MessageData.context));
61                    break;
62
63                case "Runtime.executionContextDestroyed":
64                    OnExecutionContextDestroyed((int)e.MessageData.executionContextId);
65                    break;
66                case "Runtime.executionContextsCleared":
67                    OnExecutionContextsCleared();
68                    break;
69                case "Page.lifecycleEvent":
70                    OnLifeCycleEvent(e);
71                    break;
72                default:
73                    break;
74            }
75        }
76
77        private void OnLifeCycleEvent(MessageEventArgs e)
78        {
79            if (Frames.ContainsKey(e.MessageData.frameId.ToString()))
80            {
81                Frame frame = Frames[e.MessageData.frameId.ToString()];
82
83                frame.OnLifecycleEvent(e.MessageData.loaderId.ToString(), e.MessageData.name.ToString());
84                LifecycleEvent?.Invoke(this, new FrameEventArgs(frame));
85            }
86        }
87
88        private void OnExecutionContextsCleared()
89        {
90            foreach (var context in _contextIdToContext.Values)
91            {
92                RemoveContext(context);
93            }
94            _contextIdToContext.Clear();
95        }
96
97        private void OnExecutionContextDestroyed(int executionContextId)
98        {
99            _contextIdToContext.TryGetValue(executionContextId, out var context);
100
101            if (context != null)
102            {
103                _contextIdToContext.Remove(executionContextId);
104                RemoveContext(context);
105            }
106        }
107
108        public JSHandle CreateJsHandle(int contextId, dynamic remoteObject)
109        {
110            _contextIdToContext.TryGetValue(contextId, out var storedContext);
111
112            if (storedContext == null)
113            {
114                _logger.LogError("INTERNAL ERROR: missing context with id = {ContextId}", contextId);
115            }
116
117            if (remoteObject.subtype == "node")
118            {
119                return new ElementHandle(storedContext, _client, remoteObject, _page);
120            }
121
122            return new JSHandle(storedContext, _client, remoteObject);
123        }
124
125        private void OnExecutionContextCreated(ContextPayload contextPayload)
126        {
127            var context = new ExecutionContext(_client, contextPayload,
128                remoteObject => CreateJsHandle(contextPayload.Id, remoteObject));
129
130            _contextIdToContext[contextPayload.Id] = context;
131
132            var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;
133            if (frame != null && context.IsDefault)
134            {
135                frame.SetDefaultContext(context);
136            }
137        }
138
139        private void OnFrameDetached(string frameId)
140        {
141            if (Frames.ContainsKey(frameId))
142            {
143                RemoveFramesRecursively(Frames[frameId]);
144            }
145        }
146
147        private void OnFrameNavigated(FramePayload framePayload)
148        {
149            var isMainFrame = string.IsNullOrEmpty(framePayload.ParentId);
150            var frame = isMainFrame ? MainFrame : Frames[framePayload.Id];
151
152            Contract.Assert(isMainFrame || frame != null, "We either navigate top level or have old version of the navigated frame");
153
154            // Detach all child frames first.
155            if (frame != null)
156            {
157                while (frame.ChildFrames.Count > 0)
158                {
159                    RemoveFramesRecursively(frame.ChildFrames[0]);
160                }
161            }
162
163            // Update or create main frame.
164            if (isMainFrame)
165            {
166                if (frame != null)
167                {
168                    // Update frame id to retain frame identity on cross-process navigation.
169                    if (frame.Id != null)
170                    {
171                        Frames.Remove(frame.Id);
172                    }
173                    frame.Id = framePayload.Id;
174                }
175                else
176                {
177                    // Initial main frame navigation.
178                    frame = new Frame(this._client, this._page, null, framePayload.Id);
179                }
180
181                Frames[framePayload.Id] = frame;
182                MainFrame = frame;
183            }
184
185            // Update frame payload.
186            frame.Navigated(framePayload);
187
188            FrameNavigated?.Invoke(this, new FrameEventArgs(frame));
189        }
190
191        private void RemoveContext(ExecutionContext context)
192        {
193            var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;
194
195            if (frame != null && context.IsDefault)
196            {
197                frame.SetDefaultContext(null);
198            }
199        }
200
201        private void RemoveFramesRecursively(Frame frame)
202        {
203            while (frame.ChildFrames.Count > 0)
204            {
205                RemoveFramesRecursively(frame.ChildFrames[0]);
206            }
207            frame.Detach();
208            Frames.Remove(frame.Id);
209            FrameDetached?.Invoke(this, new FrameEventArgs(frame));
210        }
211
212        private void OnFrameAttached(string frameId, string parentFrameId)
213        {
214            if (!Frames.ContainsKey(frameId) && Frames.ContainsKey(parentFrameId))
215            {
216                var parentFrame = Frames[parentFrameId];
217                var frame = new Frame(_client, _page, parentFrame, frameId);
218                Frames[frame.Id] = frame;
219                FrameAttached?.Invoke(this, new FrameEventArgs(frame));
220            }
221        }
222
223        private void HandleFrameTree(FrameTree frameTree)
224        {
225            if (!string.IsNullOrEmpty(frameTree.Frame.ParentId))
226            {
227                OnFrameAttached(frameTree.Frame.Id, frameTree.Frame.ParentId);
228            }
229
230            OnFrameNavigated(frameTree.Frame);
231
232            if (frameTree.Childs != null)
233            {
234                foreach (var child in frameTree.Childs)
235                {
236                    HandleFrameTree(child);
237                }
238            }
239        }
240
241        #endregion
242    }
243}
244
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)