/
Page.cs
executable file
·1836 lines (1626 loc) · 85.7 KB
/
Page.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.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PuppeteerSharp.Helpers;
using PuppeteerSharp.Input;
using PuppeteerSharp.Media;
using PuppeteerSharp.Messaging;
using PuppeteerSharp.Mobile;
using PuppeteerSharp.PageCoverage;
namespace PuppeteerSharp
{
/// <summary>
/// Provides methods to interact with a single tab in Chromium. One <see cref="Browser"/> instance might have multiple <see cref="Page"/> instances.
/// </summary>
/// <example>
/// This example creates a page, navigates it to a URL, and then saves a screenshot:
/// <code>
/// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
/// var page = await browser.NewPageAsync();
/// await page.GoToAsync("https://example.com");
/// await page.ScreenshotAsync("screenshot.png");
/// await browser.CloseAsync();
/// </code>
/// </example>
[DebuggerDisplay("Page {Url}")]
public class Page : IDisposable
{
private readonly bool _ignoreHTTPSErrors;
private readonly NetworkManager _networkManager;
private readonly FrameManager _frameManager;
private readonly TaskQueue _screenshotTaskQueue;
private readonly EmulationManager _emulationManager;
private readonly Dictionary<string, Delegate> _pageBindings;
private readonly ILogger _logger;
private static readonly Dictionary<string, decimal> _unitToPixels = new Dictionary<string, decimal> {
{"px", 1},
{"in", 96},
{"cm", 37.8m},
{"mm", 3.78m}
};
private Page(CDPSession client, Target target, FrameTree frameTree, bool ignoreHTTPSErrors, TaskQueue screenshotTaskQueue)
{
Client = client;
Target = target;
Keyboard = new Keyboard(client);
Mouse = new Mouse(client, Keyboard);
Touchscreen = new Touchscreen(client, Keyboard);
Tracing = new Tracing(client);
Coverage = new Coverage(client);
_frameManager = new FrameManager(client, frameTree, this);
_networkManager = new NetworkManager(client, _frameManager);
_emulationManager = new EmulationManager(client);
_pageBindings = new Dictionary<string, Delegate>();
_logger = Client.Connection.LoggerFactory.CreateLogger<Page>();
_ignoreHTTPSErrors = ignoreHTTPSErrors;
_screenshotTaskQueue = screenshotTaskQueue;
_frameManager.FrameAttached += (sender, e) => FrameAttached?.Invoke(this, e);
_frameManager.FrameDetached += (sender, e) => FrameDetached?.Invoke(this, e);
_frameManager.FrameNavigated += (sender, e) => FrameNavigated?.Invoke(this, e);
_networkManager.Request += (sender, e) => Request?.Invoke(this, e);
_networkManager.RequestFailed += (sender, e) => RequestFailed?.Invoke(this, e);
_networkManager.Response += (sender, e) => Response?.Invoke(this, e);
_networkManager.RequestFinished += (sender, e) => RequestFinished?.Invoke(this, e);
target.CloseTask.ContinueWith((arg) => Close?.Invoke(this, EventArgs.Empty));
Client.MessageReceived += Client_MessageReceived;
}
internal CDPSession Client { get; }
#region Public Properties
/// <summary>
/// Raised when the JavaScript <c>load</c> <see href="https://developer.mozilla.org/en-US/docs/Web/Events/load"/> event is dispatched.
/// </summary>
public event EventHandler Load;
/// <summary>
/// Raised when the page crashes
/// </summary>
public event EventHandler<ErrorEventArgs> Error;
/// <summary>
/// Raised when the JavaScript code makes a call to <c>console.timeStamp</c>. For the list of metrics see <see cref="Page.MetricsAsync"/>.
/// </summary>
public event EventHandler<MetricEventArgs> Metrics;
/// <summary>
/// Raised when a JavaScript dialog appears, such as <c>alert</c>, <c>prompt</c>, <c>confirm</c> or <c>beforeunload</c>. Puppeteer can respond to the dialog via <see cref="Dialog"/>'s <see cref="Dialog.Accept(string)"/> or <see cref="Dialog.Dismiss"/> methods.
/// </summary>
public event EventHandler<DialogEventArgs> Dialog;
/// <summary>
/// Raised when the JavaScript <c>DOMContentLoaded</c> <see href="https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded"/> event is dispatched.
/// </summary>
public event EventHandler DOMContentLoaded;
/// <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[
/// page.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>
public event EventHandler<ResponseCreatedEventArgs> Response;
/// <summary>
/// Raised when a page 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 an uncaught exception happens within the page.
/// </summary>
public event EventHandler<PageErrorEventArgs> PageError;
/// <summary>
/// Raised when the page closes.
/// </summary>
public event EventHandler Close;
/// <summary>
/// This setting will change the default maximum navigation time of 30 seconds for the following methods:
/// - <see cref="GoToAsync(string, NavigationOptions)"/>
/// - <see cref="GoBackAsync(NavigationOptions)"/>
/// - <see cref="GoForwardAsync(NavigationOptions)"/>
/// - <see cref="ReloadAsync(NavigationOptions)"/>
/// - <see cref="WaitForNavigationAsync(NavigationOptions)"/>
/// </summary>
public int DefaultNavigationTimeout { get; set; } = 30000;
/// <summary>
/// Gets page's main frame
/// </summary>
/// <remarks>
/// Page is guaranteed to have a main frame which persists during navigations.
/// </remarks>
public Frame MainFrame => _frameManager.MainFrame;
/// <summary>
/// Gets all frames attached to the page.
/// </summary>
/// <value>An array of all frames attached to the page.</value>
public Frame[] Frames => _frameManager.Frames.Values.ToArray();
/// <summary>
/// Shortcut for <c>page.MainFrame.Url</c>
/// </summary>
public string Url => MainFrame.Url;
/// <summary>
/// Gets that target this page was created from.
/// </summary>
public Target Target { get; }
/// <summary>
/// Gets this page's keyboard
/// </summary>
public Keyboard Keyboard { get; }
/// <summary>
/// Gets this page's touchscreen
/// </summary>
public Touchscreen Touchscreen { get; }
/// <summary>
/// Gets this page's coverage
/// </summary>
public Coverage Coverage { get; }
/// <summary>
/// Gets this page's tracing
/// </summary>
public Tracing Tracing { get; }
/// <summary>
/// Gets this page's mouse
/// </summary>
public Mouse Mouse { get; }
/// <summary>
/// Gets this page's viewport
/// </summary>
public ViewPortOptions Viewport { get; private set; }
/// <summary>
/// List of suported 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 the browser the page belongs to.
/// </summary>
public Browser Browser => Target.Browser;
#endregion
#region Public Methods
/// <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 Client.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 page. 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>page.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 page. 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="Extensions.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>page.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>
/// var overrideNavigatorLanguages = @"Object.defineProperty(navigator, 'languages', {
/// get: function() {
/// return ['en-US', 'en', 'bn'];
/// };
/// });";
/// await page.EvaluateOnNewDocumentAsync(overrideNavigatorLanguages);
/// </code>
/// </example>
/// <returns>Task</returns>
public Task EvaluateOnNewDocumentAsync(string pageFunction, params object[] args)
{
var source = EvaluationString(pageFunction, args);
return Client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new { source });
}
/// <summary>
/// The method iterates JavaScript heap and finds all the objects with the given prototype.
/// Shortcut for <c>page.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)
=> _networkManager.SetRequestInterceptionAsync(value);
/// <summary>
/// Set offline mode for the page.
/// </summary>
/// <returns>Result task</returns>
/// <param name="value">When <c>true</c> enables offline mode for the page.</param>
public Task SetOfflineModeAsync(bool value) => _networkManager.SetOfflineModeAsync(value);
/// <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)
{
var response = await Client.SendAsync("Network.getCookies", new Dictionary<string, object>
{
{ "urls", urls.Length > 0 ? urls : new string[] { Url } }
}).ConfigureAwait(false);
return response.cookies.ToObject<CookieParam[]>();
}
/// <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)
{
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 Client.SendAsync("Network.setCookies", new Dictionary<string, object>
{
{ "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)
{
var pageURL = Url;
foreach (var cookie in cookies)
{
if (string.IsNullOrEmpty(cookie.Url) && pageURL.StartsWith("http", StringComparison.Ordinal))
{
cookie.Url = pageURL;
}
await Client.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>page.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.AddScriptTag(AddTagOptions)"/>
public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options) => MainFrame.AddScriptTag(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>page.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>page.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>
/// <seealso cref="Frame.AddStyleTag(AddTagOptions)"/>
public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options) => MainFrame.AddStyleTag(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>page.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="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T">The parameter 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="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T2">The second parameter 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="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <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>
/// <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="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <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>
/// <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 page.</param>
/// <returns>Task.</returns>
/// <seealso cref="Frame.SetContentAsync(string)"/>
public Task SetContentAsync(string html) => _frameManager.MainFrame.SetContentAsync(html);
/// <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="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 async Task<Response> GoToAsync(string url, NavigationOptions options)
{
var referrer = _networkManager.ExtraHTTPHeaders?.GetValueOrDefault("referer");
var requests = new Dictionary<string, Request>();
void createRequestEventListener(object sender, RequestEventArgs e)
{
if (!requests.ContainsKey(e.Request.Url))
{
requests.Add(e.Request.Url, e.Request);
}
}
_networkManager.Request += createRequestEventListener;
var mainFrame = _frameManager.MainFrame;
var timeout = options?.Timeout ?? DefaultNavigationTimeout;
var watcher = new NavigatorWatcher(_frameManager, mainFrame, timeout, options);
var navigateTask = Navigate(Client, url, referrer);
await Task.WhenAny(
watcher.NavigationTask,
navigateTask).ConfigureAwait(false);
AggregateException exception = null;
if (navigateTask.IsFaulted)
{
exception = navigateTask.Exception;
}
else if (watcher.NavigationTask.IsCompleted &&
watcher.NavigationTask.Result.IsFaulted)
{
exception = watcher.NavigationTask.Result?.Exception;
}
if (exception == null)
{
await Task.WhenAll(
watcher.NavigationTask,
navigateTask).ConfigureAwait(false);
exception = navigateTask.Exception ?? watcher.NavigationTask.Result.Exception;
}
watcher.Cancel();
_networkManager.Request -= createRequestEventListener;
if (exception != null)
{
throw new NavigationException(exception.InnerException.Message, exception.InnerException);
}
requests.TryGetValue(MainFrame.NavigationURL, out var request);
return request?.Response;
}
/// <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>
/// 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="EmulateMediaAsync(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="EmulateMediaAsync(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)
{
var data = await PdfDataAsync(options).ConfigureAwait(false);
using (var fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 4096, true))
{
await fs.WriteAsync(data, 0, data.Length).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="EmulateMediaAsync(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="EmulateMediaAsync(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="EmulateMediaAsync(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="EmulateMediaAsync(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 async Task<byte[]> PdfDataAsync(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);
JObject result = await Client.SendAsync("Page.printToPDF", new
{
landscape = options.Landscape,
displayHeaderFooter = options.DisplayHeaderFooter,
headerTemplate = options.HeaderTemplate,
footerTemplate = options.FooterTemplate,
printBackground = options.PrintBackground,
scale = options.Scale,
paperWidth,
paperHeight,
marginTop,
marginBottom,
marginLeft,
marginRight,
pageRanges = options.PageRanges
}).ConfigureAwait(false);
var buffer = Convert.FromBase64String(result.GetValue("data").Value<string>());
return buffer;
}
/// <summary>
/// Enables/Disables Javascript on the page
/// </summary>
/// <returns>Task.</returns>
/// <param name="enabled">Whether or not to enable JavaScript on the page.</param>
public Task SetJavaScriptEnabledAsync(bool enabled)
=> Client.SendAsync("Emulation.setScriptExecutionDisabled", new { value = !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) => Client.SendAsync("Page.setBypassCSP", new { enabled });
/// <summary>
/// Emulates a media such as screen or print.
/// </summary>
/// <returns>Task.</returns>
/// <param name="media">Media to set.</param>
public Task EmulateMediaAsync(MediaType media)
=> Client.SendAsync("Emulation.setEmulatedMedia", new { media });
/// <summary>
/// Sets the viewport.
/// In the case of multiple pages in a single browser, each page can have its own viewport size.
/// NOTE in certain cases, setting viewport will reload the page in order to set the isMobile or hasTouch properties.
/// </summary>
/// <returns>The viewport task.</returns>
/// <param name="viewport">Viewport options.</param>
public async Task SetViewportAsync(ViewPortOptions viewport)
{
var needsReload = await _emulationManager.EmulateViewport(viewport).ConfigureAwait(false);
Viewport = viewport;
if (needsReload)
{
await ReloadAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Emulates given device metrics and user agent.
/// </summary>
/// <remarks>
/// This method is a shortcut for calling two methods:
/// page.SetViewportAsync(userAgent)
/// page.SetUserAgentAsync(viewport)
/// </remarks>
/// <returns>Task.</returns>
/// <param name="options">Emulation options.</param>
public Task EmulateAsync(DeviceDescriptor options) => Task.WhenAll(
SetViewportAsync(options.ViewPort),
SetUserAgentAsync(options.UserAgent)
);
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>The screenshot task.</returns>
/// <param name="file">The file path to save the image to. The screenshot type will be inferred from file extension.
/// If path is a relative path, then it is resolved relative to current working directory. If no path is provided,
/// the image won't be saved to the disk.</param>
public Task ScreenshotAsync(string file) => ScreenshotAsync(file, new ScreenshotOptions());
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>The screenshot task.</returns>
/// <param name="file">The file path to save the image to. The screenshot type will be inferred from file extension.
/// If path is a relative path, then it is resolved relative to current working directory. If no path is provided,
/// the image won't be saved to the disk.</param>
/// <param name="options">Screenshot options.</param>
public async Task ScreenshotAsync(string file, ScreenshotOptions options)
{
if (!options.Type.HasValue)
{
options.Type = ScreenshotOptions.GetScreenshotTypeFromFile(file);
}
var data = await ScreenshotDataAsync(options).ConfigureAwait(false);
using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, true))
{
await fs.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
}
}
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="Stream"/> containing the image data.</returns>
public Task<Stream> ScreenshotStreamAsync() => ScreenshotStreamAsync(new ScreenshotOptions());
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="Stream"/> containing the image data.</returns>
/// <param name="options">Screenshot options.</param>
public async Task<Stream> ScreenshotStreamAsync(ScreenshotOptions options)
=> new MemoryStream(await ScreenshotDataAsync(options).ConfigureAwait(false));
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="byte"/>[] containing the image data.</returns>
public Task<byte[]> ScreenshotDataAsync() => ScreenshotDataAsync(new ScreenshotOptions());
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="byte"/>[] containing the image data.</returns>
/// <param name="options">Screenshot options.</param>
public Task<byte[]> ScreenshotDataAsync(ScreenshotOptions options)
{
var screenshotType = options.Type;
if (!screenshotType.HasValue)
{
screenshotType = ScreenshotType.Png;
}
if (options.Quality.HasValue)
{
if (screenshotType != ScreenshotType.Jpeg)
{
throw new ArgumentException($"options.Quality is unsupported for the {screenshotType} screenshots");
}
if (options.Quality < 0 || options.Quality > 100)
{
throw new ArgumentException($"Expected options.quality to be between 0 and 100 (inclusive), got {options.Quality}");
}
}
if (options.Clip != null && options.FullPage)
{
throw new ArgumentException("options.clip and options.fullPage are exclusive");
}
return _screenshotTaskQueue.Enqueue(() => PerformScreenshot(screenshotType.Value, options));
}
/// <summary>
/// Returns page's title
/// </summary>
/// <returns>page's title</returns>
/// <see cref="Frame.GetTitleAsync"/>
public Task<string> GetTitleAsync() => MainFrame.GetTitleAsync();
/// <summary>
/// Closes the page.
/// </summary>
/// <returns>Task.</returns>
public Task CloseAsync(PageCloseOptions options = null)
{
if (!(Client?.Connection?.IsClosed ?? true))