forked from hardkoded/puppeteer-sharp
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathDevToolsContext.cs
2694 lines (2402 loc) · 125 KB
/
DevToolsContext.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Timers;
using CefSharp.Dom.Helpers;
using CefSharp.Dom.Helpers.Json;
using CefSharp.Dom.Input;
using CefSharp.Dom.Media;
using CefSharp.Dom.Messaging;
using CefSharp.Dom.Mobile;
using CefSharp.Dom.PageCoverage;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CefSharp.Dom
{
/// <summary>
/// Provides methods to interact with a ChromiumWebBrowser instance
/// </summary>
/// <example>
/// This example creates a devToolsContext, navigates it to a URL, and then saves a screenshot:
/// <code>
/// var devToolsContext = await chromiumWebBrowser.GetDevToolsContextAsync();
/// await devToolsContext.GoToAsync("https://example.com");
/// await devToolsContext.ScreenshotAsync("screenshot.png");
/// </code>
/// </example>
[DebuggerDisplay("DevToolsContext {Url}")]
public class DevToolsContext : IDisposable, IAsyncDisposable, IDevToolsContext
{
private readonly EmulationManager _emulationManager;
private readonly Dictionary<string, Delegate> _pageBindings;
private readonly ILogger _logger;
private readonly TimeoutSettings _timeoutSettings;
private readonly ConcurrentDictionary<Guid, TaskCompletionSource<FileChooser>> _fileChooserInterceptors;
private PageGetLayoutMetricsResponse _burstModeMetrics;
private bool _screenshotBurstModeOn;
private ScreenshotOptions _screenshotBurstModeOptions;
private bool _frameTreeLoaded;
private static readonly Dictionary<string, decimal> _unitToPixels = new Dictionary<string, decimal> {
{ "px", 1 },
{ "in", 96 },
{ "cm", 37.8m },
{ "mm", 3.78m }
};
internal DevToolsContext(
DevToolsConnection client)
{
Connection = client;
Keyboard = new Keyboard(client);
Mouse = new Mouse(client, Keyboard);
Touchscreen = new Touchscreen(client, Keyboard);
Tracing = new Tracing(client);
Coverage = new Coverage(client);
_fileChooserInterceptors = new ConcurrentDictionary<Guid, TaskCompletionSource<FileChooser>>();
_timeoutSettings = new TimeoutSettings();
_emulationManager = new EmulationManager(client);
_pageBindings = new Dictionary<string, Delegate>();
_logger = Connection.LoggerFactory.CreateLogger<DevToolsContext>();
Accessibility = new PageAccessibility.Accessibility(client);
}
/// <inheritdoc/>
public bool IsDisposed { get; private set; }
/// <inheritdoc/>
public DevToolsConnection Connection { get; }
/// <inheritdoc/>
public event EventHandler Load;
/// <inheritdoc/>
public event EventHandler<ErrorEventArgs> Error;
/// <inheritdoc/>
public event EventHandler<MetricEventArgs> Metrics;
/// <inheritdoc/>
public event EventHandler DOMContentLoaded;
/// <inheritdoc/>
public event EventHandler<LifecycleEventArgs> LifecycleEvent;
/// <summary>
/// Raised when JavaScript within the page calls one of console API methods, e.g. <c>console.log</c> or <c>console.dir</c>. Also emitted if the page throws an error or a warning.
/// The arguments passed into <c>console.log</c> appear as arguments on the event handler.
/// </summary>
/// <example>
/// An example of handling <see cref="Console"/> event:
/// <code>
/// <![CDATA[
/// devToolsContext.Console += (sender, e) =>
/// {
/// for (var i = 0; i < e.Message.Args.Count; ++i)
/// {
/// System.Console.WriteLine($"{i}: {e.Message.Args[i]}");
/// }
/// }
/// ]]>
/// </code>
/// </example>
public event EventHandler<ConsoleEventArgs> Console;
/// <summary>
/// Raised when a frame is attached.
/// </summary>
public event EventHandler<FrameEventArgs> FrameAttached;
/// <summary>
/// Raised when a frame is detached.
/// </summary>
public event EventHandler<FrameEventArgs> FrameDetached;
/// <summary>
/// Raised when a frame is navigated to a new url.
/// </summary>
public event EventHandler<FrameEventArgs> FrameNavigated;
/// <summary>
/// Raised when a <see cref="Response"/> is received.
/// </summary>
/// <example>
/// An example of handling <see cref="Response"/> event:
/// <code>
/// <![CDATA[
/// var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
/// devToolsContext.Response += async(sender, e) =>
/// {
/// if (e.Response.Url.Contains("script.js"))
/// {
/// tcs.TrySetResult(await e.Response.TextAsync());
/// }
/// };
///
/// await Task.WhenAll(
/// devToolsContext.GoToAsync(TestConstants.ServerUrl + "/grid.html"),
/// tcs.Task);
/// Console.WriteLine(await tcs.Task);
/// ]]>
/// </code>
/// </example>
public event EventHandler<ResponseCreatedEventArgs> Response;
/// <summary>
/// Raised when a browser issues a request. The <see cref="Request"/> object is read-only.
/// In order to intercept and mutate requests, see <see cref="SetRequestInterceptionAsync(bool)"/>
/// </summary>
public event EventHandler<RequestEventArgs> Request;
/// <summary>
/// Raised when a request finishes successfully.
/// </summary>
public event EventHandler<RequestEventArgs> RequestFinished;
/// <summary>
/// Raised when a request fails, for example by timing out.
/// </summary>
public event EventHandler<RequestEventArgs> RequestFailed;
/// <summary>
/// Raised when a request ended up loading from cache.
/// </summary>
public event EventHandler<RequestEventArgs> RequestServedFromCache;
/// <summary>
/// Raised when an uncaught exception happens within the page.
/// </summary>
public event EventHandler<PageErrorEventArgs> PageError;
/// <summary>
/// Raised when the browser opens a new tab or window.
/// </summary>
public event EventHandler<PopupEventArgs> Popup;
/// <summary>
/// This setting will change the default maximum time for the following methods:
/// - <see cref="GoToAsync(string, NavigationOptions)"/>
/// - <see cref="GoBackAsync(NavigationOptions)"/>
/// - <see cref="GoForwardAsync(NavigationOptions)"/>
/// - <see cref="ReloadAsync(NavigationOptions)"/>
/// - <see cref="SetContentAsync(string, NavigationOptions)"/>
/// - <see cref="WaitForNavigationAsync(NavigationOptions)"/>
/// **NOTE** <see cref="DefaultNavigationTimeout"/> takes priority over <seealso cref="DefaultTimeout"/>
/// </summary>
public int DefaultNavigationTimeout
{
get => _timeoutSettings.NavigationTimeout;
set => _timeoutSettings.NavigationTimeout = value;
}
/// <summary>
/// This setting will change the default maximum times for the following methods:
/// - <see cref="GoBackAsync(NavigationOptions)"/>
/// - <see cref="GoForwardAsync(NavigationOptions)"/>
/// - <see cref="GoToAsync(string, NavigationOptions)"/>
/// - <see cref="ReloadAsync(NavigationOptions)"/>
/// - <see cref="SetContentAsync(string, NavigationOptions)"/>
/// - <see cref="WaitForFunctionAsync(string, object[])"/>
/// - <see cref="WaitForNavigationAsync(NavigationOptions)"/>
/// - <see cref="WaitForRequestAsync(string, WaitForOptions)"/>
/// - <see cref="WaitForResponseAsync(string, WaitForOptions)"/>
/// - <see cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>
/// - <see cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>
/// - <see cref="WaitForExpressionAsync(string, WaitForFunctionOptions)"/>
/// </summary>
public int DefaultTimeout
{
get => _timeoutSettings.Timeout;
set => _timeoutSettings.Timeout = value;
}
/// <summary>
/// Gets browser's main frame
/// </summary>
/// <remarks>
/// Browser is guaranteed to have a main frame which persists during navigations.
/// </remarks>
public Frame MainFrame => FrameManager.MainFrame;
/// <summary>
/// Gets all frames attached to the <see cref="DevToolsContext"/>.
/// </summary>
/// <value>An array of all frames attached to the browser.</value>
public Frame[] Frames => FrameManager.GetFrames();
/// <summary>
/// Shortcut for <c>devToolsContext.MainFrame.Url</c>
/// </summary>
public string Url => MainFrame == null ? string.Empty : MainFrame.Url;
/// <summary>
/// Gets this devToolsContext keyboard
/// </summary>
public Keyboard Keyboard { get; }
/// <summary>
/// Gets this devToolsContext touchscreen
/// </summary>
public Touchscreen Touchscreen { get; }
/// <summary>
/// Gets this devToolsContext coverage
/// </summary>
public Coverage Coverage { get; }
/// <summary>
/// Gets this devToolsContext tracing
/// </summary>
public Tracing Tracing { get; }
/// <summary>
/// Gets this devToolsContext mouse
/// </summary>
public Mouse Mouse { get; }
/// <summary>
/// Gets this devToolsContext viewport
/// </summary>
public ViewPortOptions Viewport { get; private set; }
/// <summary>
/// List of supported metrics provided by the <see cref="Metrics"/> event.
/// </summary>
public static readonly IEnumerable<string> SupportedMetrics = new List<string>
{
"Timestamp",
"Documents",
"Frames",
"JSEventListeners",
"Nodes",
"LayoutCount",
"RecalcStyleCount",
"LayoutDuration",
"RecalcStyleDuration",
"ScriptDuration",
"TaskDuration",
"JSHeapUsedSize",
"JSHeapTotalSize"
};
/// <summary>
/// Get an indication that the page has been closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets the accessibility.
/// </summary>
public PageAccessibility.Accessibility Accessibility { get; }
/// <summary>
/// `true` if drag events are being intercepted, `false` otherwise.
/// </summary>
public bool IsDragInterceptionEnabled { get; private set; }
/// <summary>
/// Is Javascript Enabled
/// </summary>
public bool JavascriptEnabled { get; set; } = true;
internal bool HasPopupEventListeners => Popup?.GetInvocationList().Any() == true;
internal FrameManager FrameManager { get; private set; }
/// <summary>
/// Whether to enable drag interception.
/// </summary>
/// <remarks>
/// Activating drag interception enables the `Input.drag`,
/// methods This provides the capability to capture drag events emitted
/// on the page, which can then be used to simulate drag-and-drop.
/// </remarks>
/// <param name="enabled">Interception enabled</param>
/// <returns>A Task that resolves when the message was confirmed by the browser</returns>
public Task SetDragInterceptionAsync(bool enabled)
{
IsDragInterceptionEnabled = enabled;
return Connection.SendAsync("Input.setInterceptDrags", new InputSetInterceptDragsRequest { Enabled = enabled });
}
/// <summary>
/// Returns metrics
/// </summary>
/// <returns>Task which resolves into a list of metrics</returns>
/// <remarks>
/// All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
/// </remarks>
public async Task<Dictionary<string, decimal>> MetricsAsync()
{
var response = await Connection.SendAsync<PerformanceGetMetricsResponse>("Performance.getMetrics").ConfigureAwait(false);
return BuildMetricsObject(response.Metrics);
}
/// <summary>
/// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Touchscreen"/> to tap in the center of the element.
/// </summary>
/// <param name="selector">A selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be clicked.</param>
/// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
/// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully tapped</returns>
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);
}
/// <summary>
/// The method runs <c>document.querySelector</c> within the <see cref="MainFrame"/>. If no element matches the selector, the return value resolve to <c>null</c>.
/// </summary>
/// <param name="selector">A selector to query page for</param>
/// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>
/// <remarks>
/// Shortcut for <c>devToolsContext.MainFrame.QuerySelectorAsync(selector)</c>
/// </remarks>
/// <seealso cref="Frame.QuerySelectorAsync(string)"/>
public Task<ElementHandle> QuerySelectorAsync(string selector)
=> MainFrame.QuerySelectorAsync(selector);
/// <summary>
/// Runs <c>document.querySelectorAll</c> within the <see cref="MainFrame"/>. If no elements match the selector, the return value resolve to <see cref="Array.Empty{T}"/>.
/// </summary>
/// <param name="selector">A selector to query page for</param>
/// <returns>Task which resolves to ElementHandles pointing to the frame elements</returns>
/// <seealso cref="Frame.QuerySelectorAllAsync(string)"/>
public Task<ElementHandle[]> QuerySelectorAllAsync(string selector)
=> MainFrame.QuerySelectorAllAsync(selector);
/// <summary>
/// A utility function to be used with <see cref="PuppeteerHandleExtensions.EvaluateFunctionAsync{T}(Task{JSHandle}, string, object[])"/>
/// </summary>
/// <param name="selector">A selector to query page for</param>
/// <returns>Task which resolves to a <see cref="JSHandle"/> of <c>document.querySelectorAll</c> result</returns>
public Task<JSHandle> QuerySelectorAllHandleAsync(string selector)
=> EvaluateFunctionHandleAsync("selector => Array.from(document.querySelectorAll(selector))", selector);
/// <summary>
/// Evaluates the XPath expression
/// </summary>
/// <param name="expression">Expression to evaluate <see href="https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"/></param>
/// <returns>Task which resolves to an array of <see cref="ElementHandle"/></returns>
/// <remarks>
/// Shortcut for <c>devToolsContext.MainFrame.XPathAsync(expression)</c>
/// </remarks>
/// <seealso cref="Frame.XPathAsync(string)"/>
public Task<ElementHandle[]> XPathAsync(string expression) => MainFrame.XPathAsync(expression);
/// <summary>
/// Executes a script in browser context
/// </summary>
/// <param name="script">Script to be evaluated in browser context</param>
/// <remarks>
/// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
/// </remarks>
/// <returns>Task which resolves to script return value</returns>
public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)
{
var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);
return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);
}
/// <summary>
/// Executes a script in browser context
/// </summary>
/// <param name="pageFunction">Script to be evaluated in browser context</param>
/// <param name="args">Function arguments</param>
/// <remarks>
/// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
/// <see cref="JSHandle"/> instances can be passed as arguments
/// </remarks>
/// <returns>Task which resolves to script return value</returns>
public async Task<JSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)
{
var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);
return await context.EvaluateFunctionHandleAsync(pageFunction, args).ConfigureAwait(false);
}
/// <summary>
/// Adds a function which would be invoked in one of the following scenarios:
/// - whenever the page is navigated
/// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame
/// </summary>
/// <param name="pageFunction">Function to be evaluated in browser context</param>
/// <param name="args">Arguments to pass to <c>pageFunction</c></param>
/// <remarks>
/// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.
/// </remarks>
/// <example>
/// An example of overriding the navigator.languages property before the page loads:
/// <code>
/// await devToolsContext.EvaluateFunctionOnNewDocumentAsync("() => window.__example = true");
/// </code>
/// </example>
/// <returns>Task</returns>
public Task EvaluateFunctionOnNewDocumentAsync(string pageFunction, params object[] args)
{
var source = EvaluationString(pageFunction, args);
return Connection.SendAsync("Page.addScriptToEvaluateOnNewDocument", new PageAddScriptToEvaluateOnNewDocumentRequest
{
Source = source
});
}
/// <summary>
/// Adds a function which would be invoked in one of the following scenarios:
/// - whenever the page is navigated
/// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame
/// </summary>
/// <param name="expression">Javascript expression to be evaluated in browser context</param>
/// <remarks>
/// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.
/// </remarks>
/// <example>
/// An example of overriding the navigator.languages property before the page loads:
/// <code>
/// await devToolsContext.EvaluateExpressionOnNewDocumentAsync("window.__example = true;");
/// </code>
/// </example>
/// <returns>Task</returns>
public Task EvaluateExpressionOnNewDocumentAsync(string expression)
=> Connection.SendAsync("Page.addScriptToEvaluateOnNewDocument", new PageAddScriptToEvaluateOnNewDocumentRequest
{
Source = expression
});
/// <summary>
/// The method iterates JavaScript heap and finds all the objects with the given prototype.
/// Shortcut for <c>devToolsContext.MainFrame.GetExecutionContextAsync().QueryObjectsAsync(prototypeHandle)</c>.
/// </summary>
/// <returns>A task which resolves to a handle to an array of objects with this prototype.</returns>
/// <param name="prototypeHandle">A handle to the object prototype.</param>
public async Task<JSHandle> QueryObjectsAsync(JSHandle prototypeHandle)
{
var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);
return await context.QueryObjectsAsync(prototypeHandle).ConfigureAwait(false);
}
/// <summary>
/// Activating request interception enables <see cref="Request.AbortAsync(RequestAbortErrorCode)">request.AbortAsync</see>,
/// <see cref="Request.ContinueAsync(Payload)">request.ContinueAsync</see> and <see cref="Request.RespondAsync(ResponseData)">request.RespondAsync</see> methods.
/// </summary>
/// <returns>The request interception task.</returns>
/// <param name="value">Whether to enable request interception..</param>
public Task SetRequestInterceptionAsync(bool value)
=> FrameManager.NetworkManager.SetRequestInterceptionAsync(value);
/// <summary>
/// Set offline mode for the browser.
/// </summary>
/// <returns>Result task</returns>
/// <param name="value">When <c>true</c> enables offline mode for the browser.</param>
public Task SetOfflineModeAsync(bool value) => FrameManager.NetworkManager.SetOfflineModeAsync(value);
/// <summary>
/// Emulates network conditions
/// </summary>
/// <param name="networkConditions">Passing <c>null</c> disables network condition emulation.</param>
/// <returns>Result task</returns>
/// <remarks>
/// **NOTE** This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644)
/// </remarks>
public Task EmulateNetworkConditionsAsync(NetworkConditions networkConditions) => FrameManager.NetworkManager.EmulateNetworkConditionsAsync(networkConditions);
/// <summary>
/// Returns the page's cookies
/// </summary>
/// <param name="urls">Url's to return cookies for</param>
/// <returns>Array of cookies</returns>
/// <remarks>
/// If no URLs are specified, this method returns cookies for the current page URL.
/// If URLs are specified, only cookies for those URLs are returned.
/// </remarks>
public async Task<CookieParam[]> GetCookiesAsync(params string[] urls)
{
if (urls == null)
{
throw new ArgumentNullException(nameof(urls));
}
var response = await Connection.SendAsync<NetworkGetCookiesResponse>("Network.getCookies", new NetworkGetCookiesRequest
{
Urls = urls.Length > 0 ? urls : new string[] { Url }
}).ConfigureAwait(false);
return response.Cookies;
}
/// <summary>
/// Clears all of the current cookies and then sets the cookies for the page
/// </summary>
/// <param name="cookies">Cookies to set</param>
/// <returns>Task</returns>
public async Task SetCookieAsync(params CookieParam[] cookies)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies));
}
foreach (var cookie in cookies)
{
if (string.IsNullOrEmpty(cookie.Url) && Url.StartsWith("http", StringComparison.Ordinal))
{
cookie.Url = Url;
}
if (cookie.Url == "about:blank")
{
throw new PuppeteerException($"Blank page can not have cookie \"{cookie.Name}\"");
}
}
await DeleteCookieAsync(cookies).ConfigureAwait(false);
if (cookies.Length > 0)
{
await Connection.SendAsync("Network.setCookies", new NetworkSetCookiesRequest
{
Cookies = cookies
}).ConfigureAwait(false);
}
}
/// <summary>
/// Deletes cookies from the page
/// </summary>
/// <param name="cookies">Cookies to delete</param>
/// <returns>Task</returns>
public async Task DeleteCookieAsync(params CookieParam[] cookies)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies));
}
var pageURL = Url;
foreach (var cookie in cookies)
{
if (string.IsNullOrEmpty(cookie.Url) && pageURL.StartsWith("http", StringComparison.Ordinal))
{
cookie.Url = pageURL;
}
await Connection.SendAsync("Network.deleteCookies", cookie).ConfigureAwait(false);
}
}
/// <summary>
/// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content
/// </summary>
/// <param name="options">add script tag options</param>
/// <remarks>
/// Shortcut for <c>devToolsContext.MainFrame.AddScriptTagAsync(options)</c>
/// </remarks>
/// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>
/// <seealso cref="Frame.AddScriptTagAsync(AddTagOptions)"/>
public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options) => MainFrame.AddScriptTagAsync(options);
/// <summary>
/// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content
/// </summary>
/// <param name="url">script url</param>
/// <remarks>
/// Shortcut for <c>devToolsContext.MainFrame.AddScriptTagAsync(new AddTagOptions { Url = url })</c>
/// </remarks>
/// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>
public Task<ElementHandle> AddScriptTagAsync(string url) => AddScriptTagAsync(new AddTagOptions { Url = url });
/// <summary>
/// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content
/// </summary>
/// <param name="options">add style tag options</param>
/// <remarks>
/// Shortcut for <c>devToolsContext.MainFrame.AddStyleTagAsync(options)</c>
/// </remarks>
/// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>
public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options) => MainFrame.AddStyleTagAsync(options);
/// <summary>
/// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content
/// </summary>
/// <param name="url">stylesheel url</param>
/// <remarks>
/// Shortcut for <c>devToolsContext.MainFrame.AddStyleTagAsync(new AddTagOptions { Url = url })</c>
/// </remarks>
/// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>
public Task<ElementHandle> AddStyleTagAsync(string url) => AddStyleTagAsync(new AddTagOptions { Url = url });
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves when <paramref name="puppeteerFunction"/> completes.
/// </summary>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync(string, Action)"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync(string name, Action puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{TResult}(string, Func{TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="T">The parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{T, TResult}(string, Func{T, TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, TResult}(string, Func{T1, T2, TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, TResult}(string, Func{T1, T2, T3, TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T4">The fourth parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, T4, TResult}(string, Func{T1, T2, T3, T4, TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Gets the full HTML contents of the page, including the doctype.
/// </summary>
/// <returns>Task which resolves to the HTML content.</returns>
/// <seealso cref="Frame.GetContentAsync"/>
public Task<string> GetContentAsync() => FrameManager.MainFrame.GetContentAsync();
/// <summary>
/// Sets the HTML markup to the page
/// </summary>
/// <param name="html">HTML markup to assign to the browser.</param>
/// <param name="options">The navigations options</param>
/// <returns>Task.</returns>
/// <seealso cref="Frame.SetContentAsync(string, NavigationOptions)"/>
public Task SetContentAsync(string html, NavigationOptions options = null) => FrameManager.MainFrame.SetContentAsync(html, options);
/// <summary>
/// Navigates to an url
/// </summary>
/// <remarks>
/// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will throw an error if:
/// - there's an SSL error (e.g. in case of self-signed certificates).
/// - target URL is invalid.
/// - the `timeout` is exceeded during navigation.
/// - the remote server does not respond or is unreachable.
/// - the main resource failed to load.
///
/// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will not throw an error when any valid HTTP status code is returned by the remote server,
/// including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling <see cref="Response.Status"/>
///
/// > **NOTE** <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> either throws an error or returns a main resource response.
/// The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
///
/// > **NOTE** Headless mode doesn't support navigation to a PDF document. See the <see fref="https://bugs.chromium.org/p/chromium/issues/detail?id=761295">upstream issue</see>.
///
/// Shortcut for <seealso cref="Frame.GoToAsync(string, int?, WaitUntilNavigation[])"/>
/// </remarks>
/// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>
/// <param name="options">Navigation parameters.</param>
/// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.</returns>
/// <seealso cref="GoToAsync(string, int?, WaitUntilNavigation[])"/>
public Task<Response> GoToAsync(string url, NavigationOptions options) => FrameManager.MainFrame.GoToAsync(url, options);
/// <summary>
/// Navigates to an url
/// </summary>
/// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>
/// <param name="timeout">Maximum navigation time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout. </param>
/// <param name="waitUntil">When to consider navigation succeeded, defaults to <see cref="WaitUntilNavigation.Load"/>. Given an array of <see cref="WaitUntilNavigation"/>, navigation is considered to be successful after all events have been fired</param>
/// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>
/// <seealso cref="GoToAsync(string, NavigationOptions)"/>
public Task<Response> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)
=> GoToAsync(url, new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });
/// <summary>
/// Navigates to an url
/// </summary>
/// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>
/// <param name="waitUntil">When to consider navigation succeeded.</param>
/// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>
/// <seealso cref="GoToAsync(string, NavigationOptions)"/>
public Task<Response> GoToAsync(string url, WaitUntilNavigation waitUntil)
=> GoToAsync(url, new NavigationOptions { WaitUntil = new[] { waitUntil } });
/// <summary>
/// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaTypeAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>
/// <returns></returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public Task PdfAsync(string file) => PdfAsync(file, new PdfOptions());
/// <summary>
/// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaTypeAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>
/// <param name="options">pdf options</param>
/// <returns></returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public async Task PdfAsync(string file, PdfOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
await PdfInternalAsync(file, options).ConfigureAwait(false);
}
/// <summary>
/// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaTypeAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public Task<Stream> PdfStreamAsync() => PdfStreamAsync(new PdfOptions());
/// <summary>
/// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaTypeAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <param name="options">pdf options</param>
/// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public async Task<Stream> PdfStreamAsync(PdfOptions options)
=> new MemoryStream(await PdfDataAsync(options).ConfigureAwait(false));
/// <summary>
/// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaTypeAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public Task<byte[]> PdfDataAsync() => PdfDataAsync(new PdfOptions());
/// <summary>
/// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaTypeAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <param name="options">pdf options</param>
/// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public Task<byte[]> PdfDataAsync(PdfOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return PdfInternalAsync(null, options);
}
internal async Task<byte[]> PdfInternalAsync(string file, PdfOptions options)
{
var paperWidth = PaperFormat.Letter.Width;
var paperHeight = PaperFormat.Letter.Height;
if (options.Format != null)
{
paperWidth = options.Format.Width;
paperHeight = options.Format.Height;
}
else
{
if (options.Width != null)
{
paperWidth = ConvertPrintParameterToInches(options.Width);
}
if (options.Height != null)
{
paperHeight = ConvertPrintParameterToInches(options.Height);
}
}
var marginTop = ConvertPrintParameterToInches(options.MarginOptions.Top);
var marginLeft = ConvertPrintParameterToInches(options.MarginOptions.Left);
var marginBottom = ConvertPrintParameterToInches(options.MarginOptions.Bottom);
var marginRight = ConvertPrintParameterToInches(options.MarginOptions.Right);
if (options.OmitBackground)
{
await SetTransparentBackgroundColorAsync().ConfigureAwait(false);
}
var result = await Connection.SendAsync<PagePrintToPDFResponse>("Page.printToPDF", new PagePrintToPDFRequest
{
TransferMode = "ReturnAsStream",
Landscape = options.Landscape,
DisplayHeaderFooter = options.DisplayHeaderFooter,
HeaderTemplate = options.HeaderTemplate,
FooterTemplate = options.FooterTemplate,
PrintBackground = options.PrintBackground,
Scale = options.Scale,
PaperWidth = paperWidth,
PaperHeight = paperHeight,
MarginTop = marginTop,
MarginBottom = marginBottom,
MarginLeft = marginLeft,
MarginRight = marginRight,
PageRanges = options.PageRanges,
PreferCSSPageSize = options.PreferCSSPageSize
}).ConfigureAwait(false);
if (options.OmitBackground)
{
await ResetDefaultBackgroundColorAsync().ConfigureAwait(false);
}
return await ProtocolStreamReader.ReadProtocolStreamByteAsync(Connection, result.Stream, file).ConfigureAwait(false);
}
/// <summary>
/// Requests that page scale factor is reset to initial values.
/// </summary>
/// <returns>Task.</returns>
public Task ResetPageScaleFactorAsync()
{
return Connection.SendAsync("Emulation.resetPageScaleFactor");
}
/// <summary>
/// Sets a specified page scale factor.
/// </summary>
/// <param name="pageScaleFactor">Page scale factor.</param>
/// <returns>Task.</returns>
public Task SetPageScaleFactorAsync(double pageScaleFactor)
{
return Connection.SendAsync("Emulation.setPageScaleFactor", new EmulationSetPageScaleFactor { PageScaleFactor = pageScaleFactor });
}
/// <summary>
/// Enables/Disables Javascript on the page
/// </summary>
/// <returns>Task.</returns>
/// <param name="enabled">Whether or not to enable JavaScript on the browser.</param>
public Task SetJavaScriptEnabledAsync(bool enabled)
{
if (enabled == JavascriptEnabled)
{
return Task.CompletedTask;
}
JavascriptEnabled = enabled;
return Connection.SendAsync("Emulation.setScriptExecutionDisabled", new EmulationSetScriptExecutionDisabledRequest
{
Value = !enabled
});
}
/// <summary>
/// Automatically render all web contents using a dark theme.
/// </summary>
/// <param name="enabled">Whether to enable or disable automatic dark mode. If not specified, any existing override will be cleared.</param>
/// <returns>Task.</returns>
public Task SetAutoDarkModeOverrideAsync(bool? enabled)
{
return Connection.SendAsync("Emulation.setAutoDarkModeOverride", new SetAutoDarkModeOverrideRequest
{
Enabled = enabled
});
}
/// <summary>
/// Toggles bypassing page's Content-Security-Policy.
/// </summary>
/// <param name="enabled">sets bypassing of page's Content-Security-Policy.</param>
/// <returns></returns>
/// <remarks>
/// CSP bypassing happens at the moment of CSP initialization rather then evaluation.
/// Usually this means that <see cref="SetBypassCSPAsync(bool)"/> should be called before navigating to the domain.
/// </remarks>
public Task SetBypassCSPAsync(bool enabled) => Connection.SendAsync("Page.setBypassCSP", new PageSetBypassCSPRequest
{
Enabled = enabled