-
-
Notifications
You must be signed in to change notification settings - Fork 436
/
Frame.cs
415 lines (319 loc) · 14 KB
/
Frame.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using PuppeteerSharp.Helpers;
using PuppeteerSharp.Input;
namespace PuppeteerSharp
{
/// <inheritdoc cref="PuppeteerSharp.IFrame" />
public abstract class Frame : IFrame, IEnvironment
{
private Task<ElementHandle> _documentTask;
/// <inheritdoc />
public event EventHandler FrameSwappedByActivation;
internal event EventHandler FrameDetached;
internal event EventHandler<FrameNavigatedEventArgs> FrameNavigated;
internal event EventHandler FrameNavigatedWithinDocument;
internal event EventHandler LifecycleEvent;
internal event EventHandler FrameSwapped;
/// <inheritdoc/>
public abstract IReadOnlyCollection<IFrame> ChildFrames { get; }
/// <inheritdoc/>
public string Name { get; private set; }
/// <inheritdoc/>
public string Url { get; private set; } = string.Empty;
/// <inheritdoc/>
public bool Detached { get; private set; }
/// <inheritdoc/>
public abstract IPage Page { get; }
/// <inheritdoc/>
IFrame IFrame.ParentFrame => ParentFrame;
/// <inheritdoc/>
public abstract bool IsOopFrame { get; }
/// <inheritdoc/>
public string Id { get; internal set; }
/// <inheritdoc/>
public abstract CDPSession Client { get; protected set; }
/// <inheritdoc/>
Realm IEnvironment.MainRealm => MainRealm;
internal string ParentId { get; init; }
internal string LoaderId { get; private set; } = string.Empty;
internal List<string> LifecycleEvents { get; } = new();
internal Realm MainRealm { get; set; }
internal Realm IsolatedRealm { get; set; }
internal IsolatedWorld MainWorld => MainRealm as IsolatedWorld;
internal IsolatedWorld PuppeteerWorld => IsolatedRealm as IsolatedWorld;
internal bool HasStartedLoading { get; private set; }
internal abstract Frame ParentFrame { get; }
/// <summary>
/// Logger.
/// </summary>
protected ILogger Logger { get; init; }
/// <inheritdoc/>
public abstract Task<IResponse> GoToAsync(string url, NavigationOptions options);
/// <inheritdoc/>
public Task<IResponse> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)
=> GoToAsync(url, new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });
/// <inheritdoc/>
public abstract Task<IResponse> WaitForNavigationAsync(NavigationOptions options = null);
/// <inheritdoc/>
public Task<JToken> EvaluateExpressionAsync(string script) => MainRealm.EvaluateExpressionAsync(script);
/// <inheritdoc/>
public Task<T> EvaluateExpressionAsync<T>(string script) => MainRealm.EvaluateExpressionAsync<T>(script);
/// <inheritdoc/>
public Task<JToken> EvaluateFunctionAsync(string script, params object[] args) => MainRealm.EvaluateFunctionAsync(script, args);
/// <inheritdoc/>
public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args) => MainRealm.EvaluateFunctionAsync<T>(script, args);
/// <inheritdoc/>
public Task<IJSHandle> EvaluateExpressionHandleAsync(string script) => MainRealm.EvaluateExpressionHandleAsync(script);
/// <inheritdoc/>
public Task<IJSHandle> EvaluateFunctionHandleAsync(string function, params object[] args) => MainRealm.EvaluateFunctionHandleAsync(function, args);
/// <inheritdoc/>
public async Task<IElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)
{
if (string.IsNullOrEmpty(selector))
{
throw new ArgumentNullException(nameof(selector));
}
var (updatedSelector, queryHandler) = Client.Connection.CustomQuerySelectorRegistry.GetQueryHandlerAndSelector(selector);
return await queryHandler.WaitForAsync(this, null, updatedSelector, options).ConfigureAwait(false);
}
/// <inheritdoc/>
public Task<IElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)
{
if (string.IsNullOrEmpty(xpath))
{
throw new ArgumentNullException(nameof(xpath));
}
if (xpath.StartsWith("//", StringComparison.OrdinalIgnoreCase))
{
xpath = $".{xpath}";
}
return WaitForSelectorAsync($"xpath/{xpath}", options);
}
/// <inheritdoc/>
public Task<IJSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options, params object[] args)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return MainRealm.WaitForFunctionAsync(script, options, args);
}
/// <inheritdoc/>
public Task<IJSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return MainRealm.WaitForExpressionAsync(script, options);
}
/// <inheritdoc/>
public async Task<string[]> SelectAsync(string selector, params string[] values)
{
var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);
if (handle == null)
{
throw new SelectorException($"No node found for selector: {selector}", selector);
}
return await handle.SelectAsync(values).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<IJSHandle> QuerySelectorAllHandleAsync(string selector)
{
var document = await GetDocumentAsync().ConfigureAwait(false);
return await document.QuerySelectorAllHandleAsync(selector).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<IElementHandle> QuerySelectorAsync(string selector)
{
var document = await GetDocumentAsync().ConfigureAwait(false);
return await document.QuerySelectorAsync(selector).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<IElementHandle[]> QuerySelectorAllAsync(string selector)
{
var document = await GetDocumentAsync().ConfigureAwait(false);
return await document.QuerySelectorAllAsync(selector).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<IElementHandle[]> XPathAsync(string expression)
{
var document = await GetDocumentAsync().ConfigureAwait(false);
return await document.XPathAsync(expression).ConfigureAwait(false);
}
/// <inheritdoc/>
public Task<DeviceRequestPrompt> WaitForDevicePromptAsync(WaitForOptions options = default)
=> GetDeviceRequestPromptManager().WaitForDevicePromptAsync(options);
/// <inheritdoc/>
public abstract Task<IElementHandle> AddStyleTagAsync(AddTagOptions options);
/// <inheritdoc/>
public abstract Task<IElementHandle> AddScriptTagAsync(AddTagOptions options);
/// <inheritdoc/>
public Task<string> GetContentAsync()
=> EvaluateFunctionAsync<string>(@"() => {
let content = '';
for (const node of document.childNodes) {
switch (node) {
case document.documentElement:
content += document.documentElement.outerHTML;
break;
default:
content += new XMLSerializer().serializeToString(node);
break;
}
}
return content;
}");
/// <inheritdoc/>
public abstract Task SetContentAsync(string html, NavigationOptions options = null);
/// <inheritdoc/>
public Task<string> GetTitleAsync() => IsolatedRealm.EvaluateExpressionAsync<string>("document.title");
/// <inheritdoc/>
public async Task ClickAsync(string selector, ClickOptions options = null)
{
var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);
if (handle == null)
{
throw new SelectorException($"No node found for selector: {selector}", selector);
}
await handle.ClickAsync(options).ConfigureAwait(false);
await handle.DisposeAsync().ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task HoverAsync(string selector)
{
var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);
if (handle == null)
{
throw new SelectorException($"No node found for selector: {selector}", selector);
}
await handle.HoverAsync().ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task FocusAsync(string selector)
{
var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);
if (handle == null)
{
throw new SelectorException($"No node found for selector: {selector}", selector);
}
await handle.FocusAsync().ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task TapAsync(string selector)
{
var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);
if (handle == null)
{
throw new SelectorException($"No node found for selector: {selector}", selector);
}
await handle.TapAsync().ConfigureAwait(false);
await handle.DisposeAsync().ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task TypeAsync(string selector, string text, TypeOptions options = null)
{
var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);
if (handle == null)
{
throw new SelectorException($"No node found for selector: {selector}", selector);
}
await handle.TypeAsync(text, options).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<ElementHandle> FrameElementAsync()
{
var parentFrame = ParentFrame;
if (parentFrame == null)
{
return null;
}
var list = await parentFrame.IsolatedRealm.EvaluateFunctionHandleAsync(@"() => {
return document.querySelectorAll('iframe, frame');
}").ConfigureAwait(false);
await foreach (var iframe in list.TransposeIterableHandleAsync())
{
var frame = await iframe.ContentFrameAsync().ConfigureAwait(false);
if (frame?.Id == Id)
{
return iframe as ElementHandle;
}
try
{
await iframe.DisposeAsync().ConfigureAwait(false);
}
catch
{
Logger.LogWarning("FrameElementAsync: Error disposing iframe");
}
}
return null;
}
internal void ClearDocumentHandle() => _documentTask = null;
internal void OnLoadingStarted() => HasStartedLoading = true;
internal void OnLoadingStopped()
{
LifecycleEvents.Add("DOMContentLoaded");
LifecycleEvents.Add("load");
LifecycleEvent?.Invoke(this, EventArgs.Empty);
}
internal void OnLifecycleEvent(string loaderId, string name)
{
if (name == "init")
{
LoaderId = loaderId;
LifecycleEvents.Clear();
}
LifecycleEvents.Add(name);
LifecycleEvent?.Invoke(this, EventArgs.Empty);
}
internal void Navigated(FramePayload framePayload)
{
Name = framePayload.Name ?? string.Empty;
Url = framePayload.Url + framePayload.UrlFragment;
}
internal void OnFrameNavigated(FrameNavigatedEventArgs e) => FrameNavigated?.Invoke(this, e);
internal void OnSwapped() => FrameSwapped?.Invoke(this, EventArgs.Empty);
internal void NavigatedWithinDocument(string url)
{
Url = url;
FrameNavigatedWithinDocument?.Invoke(this, EventArgs.Empty);
}
internal void Detach()
{
Detached = true;
MainWorld.Detach();
PuppeteerWorld.Detach();
FrameDetached?.Invoke(this, EventArgs.Empty);
}
internal void OnFrameSwappedByActivation()
=> FrameSwappedByActivation?.Invoke(this, EventArgs.Empty);
/// <summary>
/// Gets the prompts manager for the current client.
/// </summary>
/// <returns>The <see cref="DeviceRequestPromptManager"/>.</returns>
protected internal abstract DeviceRequestPromptManager GetDeviceRequestPromptManager();
private Task<ElementHandle> GetDocumentAsync()
{
if (_documentTask != null)
{
return _documentTask;
}
async Task<ElementHandle> EvaluateDocumentInContext()
{
var document = await IsolatedRealm.EvaluateFunctionHandleAsync("() => document").ConfigureAwait(false);
if (document is not ElementHandle)
{
throw new PuppeteerException("Document is null");
}
return await MainRealm.TransferHandleAsync(document).ConfigureAwait(false) as ElementHandle;
}
_documentTask = EvaluateDocumentInContext();
return _documentTask;
}
}
}