How to use emulateIdleState method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

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

sidebars.js

Source: sidebars.js Github

copy
1module.exports = {
2    docs: {
3        Puppeteer: [
4            {
5              type: 'doc',
6              id: 'puppeteer.puppeteer',
7              label: 'Puppeteer',
8            },
9            {
10            Methods: [
11              {
12                type: 'doc',
13                id: 'puppeteer.puppeteer.clearcustomqueryhandlers',
14                label: 'clearcustomqueryhandlers',
15              },
16              {
17                type: 'doc',
18                id: 'puppeteer.puppeteer.connect',
19                label: 'connect',
20              },
21              {
22                type: 'doc',
23                id: 'puppeteer.puppeteer.customqueryhandlernames',
24                label: 'customqueryhandlersnames',
25              },
26              {
27                type: 'doc',
28                id: 'puppeteer.puppeteer.devices',
29                label: 'devices',
30              },
31              {
32                type: 'doc',
33                id: 'puppeteer.puppeteer.errors',
34                label: 'errors',
35              },
36              {
37                type: 'doc',
38                id: 'puppeteer.puppeteer.networkconditions',
39                label: 'networkconditions',
40              },
41              {
42                type: 'doc',
43                id: 'puppeteer.puppeteer.registercustomqueryhandler',
44                label: 'registercustomqueryhandler',
45              },
46              {
47                type: 'doc',
48                id: 'puppeteer.puppeteer.unregistercustomqueryhandler',
49                label: 'unregistercustomqueryhandler',
50              },
51            ]
52            }
53        ],
54        "BrowserFetcher": [
55            {
56              type: 'doc',
57              id: 'puppeteer.browserfetcher',
58              label: 'BrowserFetcher',
59            },
60            {
61              Methods: [
62                {
63                  type: 'doc',
64                  id: 'puppeteer.browserfetcher.candownload',
65                  label: 'candownload',
66                },
67                {
68                  type: 'doc',
69                  id: 'puppeteer.browserfetcher.download',
70                  label: 'download',
71                },
72                {
73                  type: 'doc',
74                  id: 'puppeteer.browserfetcher.host',
75                  label: 'host',
76                },
77                {
78                  type: 'doc',
79                  id: 'puppeteer.browserfetcher.localrevisions',
80                  label: 'localrevisions',
81                },
82                {
83                  type: 'doc',
84                  id: 'puppeteer.browserfetcher.platform',
85                  label: 'platform',
86                },
87                {
88                  type: 'doc',
89                  id: 'puppeteer.browserfetcher.product',
90                  label: 'product',
91                },
92                {
93                  type: 'doc',
94                  id: 'puppeteer.browserfetcher.remove',
95                  label: 'remove',
96                },
97                {
98                  type: 'doc',
99                  id: 'puppeteer.browserfetcher.revisioninfo',
100                  label: 'revisioninfo',
101                },
102              ]
103            },
104        ],
105        "Browser": [
106          {
107            type: 'doc',
108            id: 'puppeteer.browser',
109            label: 'Browser',
110          },
111          {
112            Methods: [
113              {
114                type: 'doc',
115                id: 'puppeteer.browser.browsercontexts',
116                label: 'browsercontexts',
117              },
118              {
119                type: 'doc',
120                id: 'puppeteer.browser.close',
121                label: 'close',
122              },
123              {
124                type: 'doc',
125                id: 'puppeteer.browser.createincognitobrowsercontext',
126                label: 'createincognitobrowsercontext',
127              },
128              {
129                type: 'doc',
130                id: 'puppeteer.browser.defaultbrowsercontext',
131                label: 'defaultbrowsercontext',
132              },
133              {
134                type: 'doc',
135                id: 'puppeteer.browser.disconnect',
136                label: 'disconnect',
137              },
138              {
139                type: 'doc',
140                id: 'puppeteer.browser.isconnected',
141                label: 'isconnected',
142              },
143              {
144                type: 'doc',
145                id: 'puppeteer.browser.newpage',
146                label: 'newpage',
147              },
148              {
149                type: 'doc',
150                id: 'puppeteer.browser.pages',
151                label: 'pages',
152              },
153              {
154                type: 'doc',
155                id: 'puppeteer.browser.process',
156                label: 'process',
157              },
158              {
159                type: 'doc',
160                id: 'puppeteer.browser.target',
161                label: 'target',
162              },
163              {
164                type: 'doc',
165                id: 'puppeteer.browser.useragent',
166                label: 'useragent',
167              },
168              {
169                type: 'doc',
170                id: 'puppeteer.browser.waitfortarget',
171                label: 'waitfortarget',
172              },
173              {
174                type: 'doc',
175                id: 'puppeteer.browser.wsendpoint',
176                label: 'wsendpoint',
177              },
178            ]
179          },
180        ],
181        "BrowserContext": [
182          {
183            type: 'doc',
184            id: 'puppeteer.browsercontext',
185            label: 'BrowserContext',
186          },
187          {
188            Methods: [
189              {
190                type: 'doc',
191                id: 'puppeteer.browsercontext.browser',
192                label: 'browser',
193              },
194              {
195                type: 'doc',
196                id: 'puppeteer.browsercontext.overridepermissions',
197                label: 'overridepermissions',
198              },
199              {
200                type: 'doc',
201                id: 'puppeteer.browsercontext.close',
202                label: 'close',
203              },
204              {
205                type: 'doc',
206                id: 'puppeteer.browsercontext.isincognito',
207                label: 'isincognito',
208              },
209              {
210                type: 'doc',
211                id: 'puppeteer.browsercontext.newpage',
212                label: 'newpage',
213              },
214              {
215                type: 'doc',
216                id: 'puppeteer.browsercontext.overridepermissions',
217                label: 'overridepermissions',
218              },
219              {
220                type: 'doc',
221                id: 'puppeteer.browsercontext.pages',
222                label: 'pages',
223              },
224              {
225                type: 'doc',
226                id: 'puppeteer.browsercontext.targets',
227                label: 'targets',
228              },
229              {
230                type: 'doc',
231                id: 'puppeteer.browsercontext.waitfortarget',
232                label: 'waitfortarget',
233              },
234            ]
235          },
236        ],
237        "Page": [
238          {
239            type: 'doc',
240            id: 'puppeteer.page',
241            label: 'Page',
242          },
243          {
244            Namespaces: [
245              {
246                type: 'doc',
247                id: 'puppeteer.page.accessibility',
248                label: 'accessibility',
249              },
250              {
251                type: 'doc',
252                id: 'puppeteer.page.coverage',
253                label: 'coverage',
254              },
255              {
256                type: 'doc',
257                id: 'puppeteer.page.isdraginterceptionenabled',
258                label: 'isDragInterceptionEnabled',
259              },
260              {
261                type: 'doc',
262                id: 'puppeteer.page.keyboard',
263                label: 'keyboard',
264              },
265              {
266                type: 'doc',
267                id: 'puppeteer.page.mouse',
268                label: 'mouse',
269              },
270              {
271                type: 'doc',
272                id: 'puppeteer.page.touchscreen',
273                label: 'touchScreen',
274              },
275              {
276                type: 'doc',
277                id: 'puppeteer.page.tracing',
278                label: 'tracing',
279              },
280            ]
281          },
282          {
283            Methods: [
284              {
285                type: 'doc',
286                id: 'puppeteer.page._',
287                label: '$',
288              },
289              {
290                type: 'doc',
291                id: 'puppeteer.page.__',
292                label: '$$',
293              },
294              {
295                type: 'doc',
296                id: 'puppeteer.page.__eval',
297                label: '$$eval',
298              },
299              {
300                type: 'doc',
301                id: 'puppeteer.page._eval',
302                label: '$eval',
303              },
304              {
305                type: 'doc',
306                id: 'puppeteer.page._x',
307                label: '$x',
308              },
309              {
310                type: 'doc',
311                id: 'puppeteer.page.addscripttag',
312                label: 'addScriptTag',
313              },
314              {
315                type: 'doc',
316                id: 'puppeteer.page.addstyletag',
317                label: 'addStyleTag',
318              },
319              {
320                type: 'doc',
321                id: 'puppeteer.page.authenticate',
322                label: 'authenticate',
323              },
324              {
325                type: 'doc',
326                id: 'puppeteer.page.bringtofront',
327                label: 'bringToFront',
328              },
329              {
330                type: 'doc',
331                id: 'puppeteer.page.browser',
332                label: 'browser',
333              },
334              {
335                type: 'doc',
336                id: 'puppeteer.page.browsercontext',
337                label: 'browserContext',
338              },
339              {
340                type: 'doc',
341                id: 'puppeteer.page.click',
342                label: 'click',
343              },
344              {
345                type: 'doc',
346                id: 'puppeteer.page.close',
347                label: 'close',
348              },
349              {
350                type: 'doc',
351                id: 'puppeteer.page.content',
352                label: 'content()',
353              },
354              {
355                type: 'doc',
356                id: 'puppeteer.page.cookies',
357                label: 'cookies',
358              },
359              {
360                type: 'doc',
361                id: 'puppeteer.page.createpdfstream',
362                label: 'createPDFStream',
363              },
364              {
365                type: 'doc',
366                id: 'puppeteer.page.deletecookie',
367                label: 'deleteCookie',
368              },
369              {
370                type: 'doc',
371                id: 'puppeteer.page.emulate',
372                label: 'emulate',
373              },
374              {
375                type: 'doc',
376                id: 'puppeteer.page.emulatecputhrottling',
377                label: 'emulateCPUThrottling',
378              },
379              {
380                type: 'doc',
381                id: 'puppeteer.page.emulateidlestate',
382                label: 'emulateIdleState',
383              },
384              {
385                type: 'doc',
386                id: 'puppeteer.page.emulatemediafeatures',
387                label: 'emulateMediaFeatures',
388              },
389              {
390                type: 'doc',
391                id: 'puppeteer.page.emulatenetworkconditions',
392                label: 'emulateNetworkConditions',
393              },
394              {
395                type: 'doc',
396                id: 'puppeteer.page.emulatetimezone',
397                label: 'emulateTimeZone',
398              },
399              {
400                type: 'doc',
401                id: 'puppeteer.page.emulatevisiondeficiency',
402                label: 'emulateVisionDefinciency',
403              },
404              {
405                type: 'doc',
406                id: 'puppeteer.page.evaluate',
407                label: 'evaluate',
408              },
409              {
410                type: 'doc',
411                id: 'puppeteer.page.evaluatehandle',
412                label: 'evaluateHandle',
413              },
414              {
415                type: 'doc',
416                id: 'puppeteer.page.evaluateonnewdocument',
417                label: 'evaluateOnNewDocument',
418              },
419              {
420                type: 'doc',
421                id: 'puppeteer.page.exposefunction',
422                label: 'exposeFunction',
423              },
424              {
425                type: 'doc',
426                id: 'puppeteer.page.focus',
427                label: 'focus',
428              },
429              {
430                type: 'doc',
431                id: 'puppeteer.page.frames',
432                label: 'frames',
433              },
434              {
435                type: 'doc',
436                id: 'puppeteer.page.goback',
437                label: 'goBack',
438              },
439              {
440                type: 'doc',
441                id: 'puppeteer.page.goforward',
442                label: 'goForward',
443              },
444              {
445                type: 'doc',
446                id: 'puppeteer.page.goto',
447                label: 'goTo',
448              },
449              {
450                type: 'doc',
451                id: 'puppeteer.page.hover',
452                label: 'hover',
453              },
454              {
455                type: 'doc',
456                id: 'puppeteer.page.isclosed',
457                label: 'isClosed',
458              },
459              {
460                type: 'doc',
461                id: 'puppeteer.page.isjavascriptenabled',
462                label: 'isJavaScriptEnbled',
463              },
464              {
465                type: 'doc',
466                id: 'puppeteer.page.mainframe',
467                label: 'mainFrame',
468              },
469              {
470                type: 'doc',
471                id: 'puppeteer.page.metrics',
472                label: 'metrics',
473              },
474              {
475                type: 'doc',
476                id: 'puppeteer.page.once',
477                label: 'once',
478              },
479              {
480                type: 'doc',
481                id: 'puppeteer.page.pdf',
482                label: 'PDF',
483              },
484              {
485                type: 'doc',
486                id: 'puppeteer.page.queryobjects',
487                label: 'queryObjects',
488              },
489              {
490                type: 'doc',
491                id: 'puppeteer.page.reload',
492                label: 'reload',
493              },
494              {
495                type: 'doc',
496                id: 'puppeteer.page.screenshot',
497                label: 'screenshot',
498              },
499              {
500                type: 'doc',
501                id: 'puppeteer.page.select',
502                label: 'select',
503              },
504              {
505                type: 'doc',
506                id: 'puppeteer.page.setbypasscsp',
507                label: 'setByPassCSP',
508              },
509              {
510                type: 'doc',
511                id: 'puppeteer.page.setcacheenabled',
512                label: 'setCacheEnaled',
513              },
514              {
515                type: 'doc',
516                id: 'puppeteer.page.setcontent',
517                label: 'setContent',
518              },
519              {
520                type: 'doc',
521                id: 'puppeteer.page.setcookie',
522                label: 'setCookie',
523              },
524              {
525                type: 'doc',
526                id: 'puppeteer.page.setdefaultnavigationtimeout',
527                label: 'setDefaultNavigationTimeOut',
528              },
529              {
530                type: 'doc',
531                id: 'puppeteer.page.setdefaulttimeout',
532                label: 'setDefaultTimeOut',
533              },
534              {
535                type: 'doc',
536                id: 'puppeteer.page.setdraginterception',
537                label: 'setDragInterception',
538              },
539              {
540                type: 'doc',
541                id: 'puppeteer.page.setextrahttpheaders',
542                label: 'setExtraHTTPHeader',
543              },
544              {
545                type: 'doc',
546                id: 'puppeteer.page.setgeolocation',
547                label: 'setGeoLocation',
548              },
549              {
550                type: 'doc',
551                id: 'puppeteer.page.setjavascriptenabled',
552                label: 'setJavaScriptEnabled',
553              },
554              {
555                type: 'doc',
556                id: 'puppeteer.page.setofflinemode',
557                label: 'setOfflineMode',
558              },
559              {
560                type: 'doc',
561                id: 'puppeteer.page.setrequestinterception',
562                label: 'setRequestInterception',
563              },
564              {
565                type: 'doc',
566                id: 'puppeteer.page.setuseragent',
567                label: 'setUserAgent',
568              },
569              {
570                type: 'doc',
571                id: 'puppeteer.page.setviewport',
572                label: 'setViewPort',
573              },
574              {
575                type: 'doc',
576                id: 'puppeteer.page.tap',
577                label: 'tap',
578              },
579              {
580                type: 'doc',
581                id: 'puppeteer.page.target',
582                label: 'target',
583              },
584              {
585                type: 'doc',
586                id: 'puppeteer.page.title',
587                label: 'title',
588              },
589              {
590                type: 'doc',
591                id: 'puppeteer.page.type',
592                label: 'type',
593              },
594              {
595                type: 'doc',
596                id: 'puppeteer.page.url',
597                label: 'url',
598              },
599              {
600                type: 'doc',
601                id: 'puppeteer.page.viewport',
602                label: 'viewport',
603              },
604              {
605                type: 'doc',
606                id: 'puppeteer.page.waitfor',
607                label: 'waitFor',
608              },
609              {
610                type: 'doc',
611                id: 'puppeteer.page.waitforfilechooser',
612                label: 'waitForFileChooser',
613              },
614              {
615                type: 'doc',
616                id: 'puppeteer.page.waitforfunction',
617                label: 'waitForFunction',
618              },
619              {
620                type: 'doc',
621                id: 'puppeteer.page.waitfornavigation',
622                label: 'waitForNavigation',
623              },
624              {
625                type: 'doc',
626                id: 'puppeteer.page.waitforrequest',
627                label: 'waitForRequest',
628              },
629              {
630                type: 'doc',
631                id: 'puppeteer.page.waitforresponse',
632                label: 'waitForResponse',
633              },
634              {
635                type: 'doc',
636                id: 'puppeteer.page.waitforselector',
637                label: 'waitForSelector',
638              },
639              {
640                type: 'doc',
641                id: 'puppeteer.page.waitfortimeout',
642                label: 'waittimeout',
643              },
644              {
645                type: 'doc',
646                id: 'puppeteer.page.waitforxpath',
647                label: 'waitForXPath',
648              },
649              {
650                type: 'doc',
651                id: 'puppeteer.page.workers',
652                label: 'workers',
653              },
654            ]
655          },
656        ],
657        "WebWorker": [
658          {
659            type: 'doc',
660            id: 'puppeteer.webworker',
661            label: 'WebWorker',
662          },
663          {
664            Methods: [
665              {
666                type: 'doc',
667                id: 'puppeteer.webworker.evaluate',
668                label: 'evaluate',
669              },
670              {
671                type: 'doc',
672                id: 'puppeteer.webworker.evaluatehandle',
673                label: 'evaluatehandle',
674              },
675              {
676                type: 'doc',
677                id: 'puppeteer.webworker.executioncontext',
678                label: 'executioncontext',
679              },
680              {
681                type: 'doc',
682                id: 'puppeteer.webworker.url',
683                label: 'url',
684              },
685            ]
686          },
687        ],
688        "Accessibility": [
689          {
690            type: 'doc',
691            id: 'puppeteer.accessibility',
692            label: 'Accessibility',
693          },
694          {
695            Methods: [
696              {
697                type: 'doc',
698                id: 'puppeteer.accessibility.snapshot',
699                label: 'snapshot',
700              },
701            ]
702          },
703        ],
704        "Keyboard": [
705          {
706            type: 'doc',
707            id: 'puppeteer.keyboard',
708            label: 'keyboard',
709          },
710          {
711            Methods: [
712              {
713                type: 'doc',
714                id: 'puppeteer.keyboard.down',
715                label: 'down',
716              },
717              {
718                type: 'doc',
719                id: 'puppeteer.keyboard.press',
720                label: 'press',
721              },
722              {
723                type: 'doc',
724                id: 'puppeteer.keyboard.sendcharacter',
725                label: 'sendCharacter',
726              },
727              {
728                type: 'doc',
729                id: 'puppeteer.keyboard.type',
730                label: 'type',
731              },
732              {
733                type: 'doc',
734                id: 'puppeteer.keyboard.up',
735                label: 'up',
736              },
737            ]
738          },
739        ],
740        "Mouse": [
741          {
742            type: 'doc',
743            id: 'puppeteer.mouse',
744            label: 'mouse',
745          },
746          {
747            Methods: [
748              {
749                type: 'doc',
750                id: 'puppeteer.mouse.click',
751                label: 'click',
752              },
753              {
754                type: 'doc',
755                id: 'puppeteer.mouse.down',
756                label: 'down',
757              },
758              {
759                type: 'doc',
760                id: 'puppeteer.mouse.drag',
761                label: 'drag',
762              },
763              {
764                type: 'doc',
765                id: 'puppeteer.mouse.draganddrop',
766                label: 'dragAndDrop',
767              },
768              {
769                type: 'doc',
770                id: 'puppeteer.mouse.dragenter',
771                label: 'dragEnter',
772              },
773              {
774                type: 'doc',
775                id: 'puppeteer.mouse.dragover',
776                label: 'dragOver',
777              },
778              {
779                type: 'doc',
780                id: 'puppeteer.mouse.drop',
781                label: 'drop',
782              },
783              {
784                type: 'doc',
785                id: 'puppeteer.mouse.move',
786                label: 'move',
787              },
788              {
789                type: 'doc',
790                id: 'puppeteer.mouse.up',
791                label: 'up',
792              },
793              {
794                type: 'doc',
795                id: 'puppeteer.mouse.wheel',
796                label: 'wheel',
797              },
798            ]
799          },
800        ],
801        "TouchScreen": [
802          {
803            type: 'doc',
804            id: 'puppeteer.touchscreen',
805            label: 'touchScreen',
806          },
807          {
808            Methods: [
809              {
810                type: 'doc',
811                id: 'puppeteer.touchscreen.tap',
812                label: 'tap'
813              }
814            ]
815          },
816        ],
817        "Tracing": [
818          {
819            type: 'doc',
820            id: 'puppeteer.tracing',
821            label: 'Tracing',
822          },
823          {
824            Methods: [
825              {
826                type: 'doc',
827                id: 'puppeteer.tracing._client',
828                label: 'client',
829              },
830              {
831                type: 'doc',
832                id: 'puppeteer.tracing._path',
833                label: 'path',
834              },
835              {
836                type: 'doc',
837                id: 'puppeteer.tracing._recording',
838                label: 'recording',
839              },
840              {
841                type: 'doc',
842                id: 'puppeteer.tracing.start',
843                label: 'start',
844              },
845              {
846                type: 'doc',
847                id: 'puppeteer.tracing.stop',
848                label: 'stop',
849              },
850            ]
851          },
852        ],
853        "Dialog": [
854          {
855            type: 'doc',
856            id: 'puppeteer.dialog',
857            label: 'dialog',
858          },
859          {
860            Methods: [
861              {
862                type: 'doc',
863                id: 'puppeteer.dialog.accept',
864                label: 'accept',
865              },
866              {
867                type: 'doc',
868                id: 'puppeteer.dialog.defaultvalue',
869                label: 'defaultValue',
870              },
871              {
872                type: 'doc',
873                id: 'puppeteer.dialog.dismiss',
874                label: 'dismiss',
875              },
876              {
877                type: 'doc',
878                id: 'puppeteer.dialog.message',
879                label: 'message',
880              },
881              {
882                type: 'doc',
883                id: 'puppeteer.dialog.type',
884                label: 'type',
885              },
886            ]
887          },
888        ],
889        "ConsoleMessage": [
890          {
891            type: 'doc',
892            id: 'puppeteer.consolemessage',
893            label: 'consoleMessage',
894          },
895          {
896            Methods: [
897              {
898                type: 'doc',
899                id: 'puppeteer.consolemessage.args',
900                label: 'args',
901              },
902              {
903                type: 'doc',
904                id: 'puppeteer.consolemessage.location',
905                label: 'location',
906              },
907              {
908                type: 'doc',
909                id: 'puppeteer.consolemessage.stacktrace',
910                label: 'stackTrace',
911              },
912              {
913                type: 'doc',
914                id: 'puppeteer.consolemessage.text',
915                label: 'text',
916              },
917              {
918                type: 'doc',
919                id: 'puppeteer.consolemessage.type',
920                label: 'type',
921              },
922            ]
923          },
924        ],
925        "Frame": [
926          {
927            type: 'doc',
928            id: 'puppeteer.frame',
929            label: 'frame',
930          },
931          {
932            Methods: [
933              {
934                type: 'doc',
935                id: 'puppeteer.frame._',
936                label: '$',
937              },
938              {
939                type: 'doc',
940                id: 'puppeteer.frame.__',
941                label: '$$',
942              },
943              {
944                type: 'doc',
945                id: 'puppeteer.frame.__eval',
946                label: '$$eval',
947              },
948              {
949                type: 'doc',
950                id: 'puppeteer.frame._eval',
951                label: '$eval',
952              },
953              {
954                type: 'doc',
955                id: 'puppeteer.frame._x',
956                label: '$x',
957              },
958              {
959                type: 'doc',
960                id: 'puppeteer.frame.addscripttag',
961                label: 'addScriptTag',
962              },
963              {
964                type: 'doc',
965                id: 'puppeteer.frame.addstyletag',
966                label: 'addStyleTag',
967              },
968              {
969                type: 'doc',
970                id: 'puppeteer.frame.childframes',
971                label: 'childFrames',
972              },
973              {
974                type: 'doc',
975                id: 'puppeteer.frame.click',
976                label: 'click',
977              },
978              {
979                type: 'doc',
980                id: 'puppeteer.frame.content',
981                label: 'content',
982              },
983              {
984                type: 'doc',
985                id: 'puppeteer.frame.evaluate',
986                label: 'evaluate',
987              },
988              {
989                type: 'doc',
990                id: 'puppeteer.frame.evaluatehandle',
991                label: 'evaluateHandle',
992              },
993              {
994                type: 'doc',
995                id: 'puppeteer.frame.executioncontext',
996                label: 'executionContext',
997              },
998              {
999                type: 'doc',
1000                id: 'puppeteer.frame.focus',
1001                label: 'focus',
1002              },
1003              {
1004                type: 'doc',
1005                id: 'puppeteer.frame.goto',
1006                label: 'goTo',
1007              },
1008              {
1009                type: 'doc',
1010                id: 'puppeteer.frame.hover',
1011                label: 'hover',
1012              },
1013              {
1014                type: 'doc',
1015                id: 'puppeteer.frame.isdetached',
1016                label: 'isDetached',
1017              },
1018              {
1019                type: 'doc',
1020                id: 'puppeteer.frame.name',
1021                label: 'name',
1022              },
1023              {
1024                type: 'doc',
1025                id: 'puppeteer.frame.parentframe',
1026                label: 'parentFrame',
1027              },
1028              {
1029                type: 'doc',
1030                id: 'puppeteer.frame.select',
1031                label: 'select',
1032              },
1033              {
1034                type: 'doc',
1035                id: 'puppeteer.frame.setcontent',
1036                label: 'setContent',
1037              },
1038              {
1039                type: 'doc',
1040                id: 'puppeteer.frame.tap',
1041                label: 'tap',
1042              },
1043              {
1044                type: 'doc',
1045                id: 'puppeteer.frame.title',
1046                label: 'title',
1047              },
1048              {
1049                type: 'doc',
1050                id: 'puppeteer.frame.type',
1051                label: 'type',
1052              },
1053              {
1054                type: 'doc',
1055                id: 'puppeteer.frame.url',
1056                label: 'url',
1057              },
1058              {
1059                type: 'doc',
1060                id: 'puppeteer.frame.waitfor',
1061                label: 'waitFor',
1062              },
1063              {
1064                type: 'doc',
1065                id: 'puppeteer.frame.waitforfunction',
1066                label: 'waitForFunction',
1067              },
1068              {
1069                type: 'doc',
1070                id: 'puppeteer.frame.waitfornavigation',
1071                label: 'waitForNavigation',
1072              },
1073              {
1074                type: 'doc',
1075                id: 'puppeteer.frame.waitforselector',
1076                label: 'waitForSelector',
1077              },
1078              {
1079                type: 'doc',
1080                id: 'puppeteer.frame.waitfortimeout',
1081                label: 'waitForTimeOut',
1082              },
1083              {
1084                type: 'doc',
1085                id: 'puppeteer.frame.waitforxpath',
1086                label: 'waitForXPath',
1087              },
1088            ]
1089          }
1090        ],
1091        "FileChooser": [
1092          {
1093            type: 'doc',
1094            id: 'puppeteer.filechooser',
1095            label: 'FileChooser',
1096          },
1097          {
1098            Methods: [
1099              {
1100                type: 'doc',
1101                id: 'puppeteer.filechooser.accept',
1102                label: 'accept',
1103              },
1104              {
1105                type: 'doc',
1106                id: 'puppeteer.filechooser.cancel',
1107                label: 'cancel',
1108              },
1109              {
1110                type: 'doc',
1111                id: 'puppeteer.filechooser.ismultiple',
1112                label: 'ismultiple',
1113              },
1114            ]
1115          },
1116        ],
1117        "ExecutionContext": [
1118          {
1119            type: 'doc',
1120            id: 'puppeteer.executioncontext',
1121            label: 'executionContext',
1122          },
1123          {
1124            Methods: [
1125              {
1126                type: 'doc',
1127                id: 'puppeteer.executioncontext.evaluate',
1128                label: 'evaluate',
1129              },
1130              {
1131                type: 'doc',
1132                id: 'puppeteer.executioncontext.evaluatehandle',
1133                label: 'evaluateHandle',
1134              },
1135              {
1136                type: 'doc',
1137                id: 'puppeteer.executioncontext.frame',
1138                label: 'frame',
1139              },
1140              {
1141                type: 'doc',
1142                id: 'puppeteer.executioncontext.queryobjects',
1143                label: 'queryobjects',
1144              },
1145            ]
1146          },
1147        ],
1148        "JSHandle": [
1149          {
1150            type: 'doc',
1151            id: 'puppeteer.jshandle',
1152            label: 'JSHandle',
1153          },
1154          {
1155            Methods: [
1156              {
1157                type: 'doc',
1158                id: 'puppeteer.jshandle.aselement',
1159                label: 'asElement',
1160              },
1161              {
1162                type: 'doc',
1163                id: 'puppeteer.jshandle.dispose',
1164                label: 'dispose',
1165              },
1166              {
1167                type: 'doc',
1168                id: 'puppeteer.jshandle.evaluate',
1169                label: 'evaluate',
1170              },
1171              {
1172                type: 'doc',
1173                id: 'puppeteer.jshandle.evaluatehandle',
1174                label: 'evaluateHandle',
1175              },
1176              {
1177                type: 'doc',
1178                id: 'puppeteer.jshandle.executioncontext',
1179                label: 'executionContext',
1180              },
1181              {
1182                type: 'doc',
1183                id: 'puppeteer.jshandle.getproperties',
1184                label: 'getProperties',
1185              },
1186              {
1187                type: 'doc',
1188                id: 'puppeteer.jshandle.getproperty',
1189                label: 'getProperty',
1190              },
1191              {
1192                type: 'doc',
1193                id: 'puppeteer.jshandle.jsonvalue',
1194                label: 'JSONValue',
1195              },
1196            ]
1197          },
1198        ],
1199        "ElementHandle": [
1200          {
1201            type: 'doc',
1202            id: 'puppeteer.elementhandle',
1203            label: 'elementHandle',
1204          },
1205          {
1206            Methods: [
1207              {
1208                type: 'doc',
1209                id: 'puppeteer.elementhandle._',
1210                label: '$',
1211              },
1212              {
1213                type: 'doc',
1214                id: 'puppeteer.elementhandle.__',
1215                label: '$$',
1216              },
1217              {
1218                type: 'doc',
1219                id: 'puppeteer.elementhandle.__eval',
1220                label: '$$eval',
1221              },
1222              {
1223                type: 'doc',
1224                id: 'puppeteer.elementhandle._eval',
1225                label: '$eval',
1226              },
1227              {
1228                type: 'doc',
1229                id: 'puppeteer.elementhandle._x',
1230                label: '$x',
1231              },
1232              {
1233                type: 'doc',
1234                id: 'puppeteer.elementhandle.aselement',
1235                label: 'asElement',
1236              },
1237              {
1238                type: 'doc',
1239                id: 'puppeteer.elementhandle.boundingbox',
1240                label: 'boundingBox',
1241              },
1242              {
1243                type: 'doc',
1244                id: 'puppeteer.elementhandle.boxmodel',
1245                label: 'boxModel',
1246              },
1247              {
1248                type: 'doc',
1249                id: 'puppeteer.elementhandle.click',
1250                label: 'click',
1251              },
1252              {
1253                type: 'doc',
1254                id: 'puppeteer.elementhandle.contentframe',
1255                label: 'contentFrame',
1256              },
1257              {
1258                type: 'doc',
1259                id: 'puppeteer.elementhandle.focus',
1260                label: 'focus',
1261              },
1262              {
1263                type: 'doc',
1264                id: 'puppeteer.elementhandle.hover',
1265                label: 'hover',
1266              },
1267              {
1268                type: 'doc',
1269                id: 'puppeteer.elementhandle.clickablepoint',
1270                label: 'clickablePoint',
1271              },
1272              {
1273                type: 'doc',
1274                id: 'puppeteer.elementhandle.drag',
1275                label: 'drag',
1276              },
1277              {
1278                type: 'doc',
1279                id: 'puppeteer.elementhandle.draganddrop',
1280                label: 'dragAndDrop',
1281              },
1282              {
1283                type: 'doc',
1284                id: 'puppeteer.elementhandle.dragenter',
1285                label: 'dragEnter',
1286              },
1287              {
1288                type: 'doc',
1289                id: 'puppeteer.elementhandle.dragover',
1290                label: 'dragOver',
1291              },
1292              {
1293                type: 'doc',
1294                id: 'puppeteer.elementhandle.drop',
1295                label: 'drop',
1296              },
1297              {
1298                type: 'doc',
1299                id: 'puppeteer.elementhandle.isintersectingviewport',
1300                label: 'isIntersectingViewPort',
1301              },
1302              {
1303                type: 'doc',
1304                id: 'puppeteer.elementhandle.press',
1305                label: 'press',
1306              },
1307              {
1308                type: 'doc',
1309                id: 'puppeteer.elementhandle.screenshot',
1310                label: 'screenshot',
1311              },
1312              {
1313                type: 'doc',
1314                id: 'puppeteer.elementhandle.select',
1315                label: 'select',
1316              },
1317              {
1318                type: 'doc',
1319                id: 'puppeteer.elementhandle.tap',
1320                label: 'tap',
1321              },
1322              {
1323                type: 'doc',
1324                id: 'puppeteer.elementhandle.type',
1325                label: 'type',
1326              },
1327              {
1328                type: 'doc',
1329                id: 'puppeteer.elementhandle.uploadfile',
1330                label: 'uploadFile',
1331              },
1332            ]
1333          },
1334        ],
1335        "HTTPRequest": [
1336          {
1337            type: 'doc',
1338            id: 'puppeteer.httprequest',
1339            label: 'httpRequest',
1340          },
1341          {
1342            Methods: [
1343              {
1344                type: 'doc',
1345                id: 'puppeteer.httprequest.abort',
1346                label: 'abort',
1347              },
1348              {
1349                type: 'doc',
1350                id: 'puppeteer.httprequest.aborterrorreason',
1351                label: 'abortErrorReason',
1352              },
1353              {
1354                type: 'doc',
1355                id: 'puppeteer.httprequest.enqueueinterceptaction',
1356                label: 'enqueueInterCeptaction',
1357              },
1358              {
1359                type: 'doc',
1360                id: 'puppeteer.httprequest.failure',
1361                label: 'failure',
1362              },
1363              {
1364                type: 'doc',
1365                id: 'puppeteer.httprequest.finalizeinterceptions',
1366                label: 'finalizeInterception',
1367              },
1368              {
1369                type: 'doc',
1370                id: 'puppeteer.httprequest.frame',
1371                label: 'frame',
1372              },
1373              {
1374                type: 'doc',
1375                id: 'puppeteer.httprequest.headers',
1376                label: 'headers',
1377              },
1378              {
1379                type: 'doc',
1380                id: 'puppeteer.httprequest.isnavigationrequest',
1381                label: 'isNavigationRequest',
1382              },
1383              {
1384                type: 'doc',
1385                id: 'puppeteer.httprequest.method',
1386                label: 'method',
1387              },
1388              {
1389                type: 'doc',
1390                id: 'puppeteer.httprequest.postdata',
1391                label: 'postData',
1392              },
1393              {
1394                type: 'doc',
1395                id: 'puppeteer.httprequest.redirectchain',
1396                label: 'redirectChain',
1397              },
1398              {
1399                type: 'doc',
1400                id: 'puppeteer.httprequest.resourcetype',
1401                label: 'resourceType',
1402              },
1403              {
1404                type: 'doc',
1405                id: 'puppeteer.httprequest.respond',
1406                label: 'respond',
1407              },
1408              {
1409                type: 'doc',
1410                id: 'puppeteer.httprequest.response',
1411                label: 'response',
1412              },
1413              {
1414                type: 'doc',
1415                id: 'puppeteer.httprequest.responseforrequest',
1416                label: 'responseForRequest',
1417              },
1418              {
1419                type: 'doc',
1420                id: 'puppeteer.httprequest.url',
1421                label: 'hurl',
1422              },
1423            ]
1424          },
1425        ],
1426        "HTTPRespose": [
1427          {
1428            type: 'doc',
1429            id: 'puppeteer.httpresponse',
1430            label: 'httpResponse',
1431          },
1432          {
1433            Methods: [
1434              {
1435                type: 'doc',
1436                id: 'puppeteer.httpresponse.buffer',
1437                label: 'buffer',
1438              },
1439              {
1440                type: 'doc',
1441                id: 'puppeteer.httpresponse.frame',
1442                label: 'frame',
1443              },
1444              {
1445                type: 'doc',
1446                id: 'puppeteer.httpresponse.fromcache',
1447                label: 'fromCache',
1448              },
1449              {
1450                type: 'doc',
1451                id: 'puppeteer.httpresponse.fromserviceworker',
1452                label: 'fromServiceWorker',
1453              },
1454              {
1455                type: 'doc',
1456                id: 'puppeteer.httpresponse.headers',
1457                label: 'headers',
1458              },
1459              {
1460                type: 'doc',
1461                id: 'puppeteer.httpresponse.json',
1462                label: 'JSON',
1463              },
1464              {
1465                type: 'doc',
1466                id: 'puppeteer.httpresponse.ok',
1467                label: 'OK',
1468              },
1469              {
1470                type: 'doc',
1471                id: 'puppeteer.httpresponse.remoteaddress',
1472                label: 'remoteAddress',
1473              },
1474              {
1475                type: 'doc',
1476                id: 'puppeteer.httpresponse.request',
1477                label: 'request',
1478              },
1479              {
1480                type: 'doc',
1481                id: 'puppeteer.httpresponse.securitydetails',
1482                label: 'securityDetails',
1483              },
1484              {
1485                type: 'doc',
1486                id: 'puppeteer.httpresponse.status',
1487                label: 'status',
1488              },
1489              {
1490                type: 'doc',
1491                id: 'puppeteer.httpresponse.statustext',
1492                label: 'statusText',
1493              },
1494              {
1495                type: 'doc',
1496                id: 'puppeteer.httpresponse.text',
1497                label: 'text',
1498              },
1499              {
1500                type: 'doc',
1501                id: 'puppeteer.httpresponse.url',
1502                label: 'URL',
1503              },
1504            ]
1505          },
1506        ],
1507        "SecurityDetails": [
1508          {
1509            type: 'doc',
1510            id: 'puppeteer.securitydetails',
1511            label: 'securityDetails',
1512          },
1513          {
1514            Methods: [
1515              {
1516                type: 'doc',
1517                id: 'puppeteer.securitydetails.issuer',
1518                label: 'issuer',
1519              },
1520              {
1521                type: 'doc',
1522                id: 'puppeteer.securitydetails.protocol',
1523                label: 'protocol',
1524              },
1525              {
1526                type: 'doc',
1527                id: 'puppeteer.securitydetails.subjectalternativenames',
1528                label: 'subjectAlternativeNames',
1529              },
1530              {
1531                type: 'doc',
1532                id: 'puppeteer.securitydetails.subjectname',
1533                label: 'subjectName',
1534              },
1535              {
1536                type: 'doc',
1537                id: 'puppeteer.securitydetails.validfrom',
1538                label: 'validFrom',
1539              },
1540              {
1541                type: 'doc',
1542                id: 'puppeteer.securitydetails.validto',
1543                label: 'validTo',
1544              },
1545            ]
1546          },
1547        ],
1548        "Target": [
1549          {
1550            type: 'doc',
1551            id: 'puppeteer.target',
1552            label: 'target',
1553          },
1554          {
1555            Methods: [
1556              {
1557                type: 'doc',
1558                id: 'puppeteer.target.browser',
1559                label: 'browser',
1560              },
1561              {
1562                type: 'doc',
1563                id: 'puppeteer.target.browsercontext',
1564                label: 'browserContext',
1565              },
1566              {
1567                type: 'doc',
1568                id: 'puppeteer.target.createcdpsession',
1569                label: 'createCDPSSession',
1570              },
1571              {
1572                type: 'doc',
1573                id: 'puppeteer.target.opener',
1574                label: 'opener',
1575              },
1576              {
1577                type: 'doc',
1578                id: 'puppeteer.target.page',
1579                label: 'page',
1580              },
1581              {
1582                type: 'doc',
1583                id: 'puppeteer.target.type',
1584                label: 'type',
1585              },
1586              {
1587                type: 'doc',
1588                id: 'puppeteer.target.url',
1589                label: 'url',
1590              },
1591              {
1592                type: 'doc',
1593                id: 'puppeteer.target.worker',
1594                label: 'worker',
1595              },
1596            ]
1597          },
1598        ],
1599        "CDPSession": [
1600          {
1601            type: 'doc',
1602            id: 'puppeteer.cdpsession',
1603            label: 'CDPSession',
1604          },
1605          {
1606            Methods: [
1607              {
1608                type: 'doc',
1609                id: 'puppeteer.cdpsession.connection',
1610                label: 'connection',
1611              },
1612              {
1613                type: 'doc',
1614                id: 'puppeteer.cdpsession.detach',
1615                label: 'detach',
1616              },
1617              {
1618                type: 'doc',
1619                id: 'puppeteer.cdpsession.send',
1620                label: 'send',
1621              },
1622            ]
1623          },
1624        ],
1625        "Coverage": [
1626          {
1627            type: 'doc',
1628            id: 'puppeteer.coverage',
1629            label: 'coverage',
1630          },
1631          {
1632            Methods: [
1633              {
1634                type: 'doc',
1635                id: 'puppeteer.coverage.startcsscoverage',
1636                label: 'startCSSCoverage',
1637              },
1638              {
1639                type: 'doc',
1640                id: 'puppeteer.coverage.startjscoverage',
1641                label: 'startJSCoverage',
1642              },
1643              {
1644                type: 'doc',
1645                id: 'puppeteer.coverage.stopcsscoverage',
1646                label: 'stopCSSCoverage',
1647              },
1648              {
1649                type: 'doc',
1650                id: 'puppeteer.coverage.stopjscoverage',
1651                label: 'stopJSCoverage',
1652              },
1653            ]
1654          },
1655        ],
1656        "TimeOutError": [
1657          {
1658            type: 'doc',
1659            id: 'puppeteer.timeouterror',
1660            label: 'timeOutError',
1661          },
1662        ],
1663        "EventEmitter": [
1664          {
1665            type: 'doc',
1666            id: 'puppeteer.eventemitter',
1667            label: 'eventEmitter',
1668          },
1669          {
1670            Methods: [
1671              {
1672                type: 'doc',
1673                id: 'puppeteer.eventemitter.addlistener',
1674                label: 'addListener',
1675              },
1676              {
1677                type: 'doc',
1678                id: 'puppeteer.eventemitter.emit',
1679                label: 'emit',
1680              },
1681              {
1682                type: 'doc',
1683                id: 'puppeteer.eventemitter.listenercount',
1684                label: 'listenerCount',
1685              },
1686              {
1687                type: 'doc',
1688                id: 'puppeteer.eventemitter.off',
1689                label: 'off',
1690              },
1691              {
1692                type: 'doc',
1693                id: 'puppeteer.eventemitter.on',
1694                label: 'on',
1695              },
1696              {
1697                type: 'doc',
1698                id: 'puppeteer.eventemitter.once',
1699                label: 'once',
1700              },
1701              {
1702                type: 'doc',
1703                id: 'puppeteer.eventemitter.removelistener',
1704                label: 'removeListener',
1705              },{
1706                type: 'doc',
1707                id: 'puppeteer.eventemitter.removealllisteners',
1708                label: 'removeAllListener',
1709              },
1710            ]
1711          },
1712        ],
1713    },
1714};
1715
Full Screen

Page.js

Source: Page.js Github

copy
1/**
2 * Copyright 2017 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16import { isNode } from '../environment.js';
17
18import { Accessibility } from './Accessibility.js';
19import { assert } from './assert.js';
20import { CDPSessionEmittedEvents, Connection, } from './Connection.js';
21import { ConsoleMessage } from './ConsoleMessage.js';
22import { Coverage } from './Coverage.js';
23import { Dialog } from './Dialog.js';
24import { EmulationManager } from './EmulationManager.js';
25import { EventEmitter } from './EventEmitter.js';
26import { FileChooser } from './FileChooser.js';
27import { FrameManager, FrameManagerEmittedEvents, } from './FrameManager.js';
28import { debugError , helper} from './helper.js';
29import { Keyboard, Mouse, Touchscreen } from './Input.js';
30import { createJSHandle } from './JSHandle.js';
31import { NetworkManagerEmittedEvents } from './NetworkManager.js';
32import { paperFormats } from './PDFOptions.js';
33import { TimeoutSettings } from './TimeoutSettings.js';
34import { Tracing } from './Tracing.js';
35import { WebWorker } from './WebWorker.js';
36
37class ScreenshotTaskQueue {
38    constructor() {
39        this._chain = Promise.resolve(undefined);
40    }
41    postTask(task) {
42        const result = this._chain.then(task);
43        this._chain = result.catch(() => { });
44        return result;
45    }
46}
47/**
48 * Page provides methods to interact with a single tab or
49 * {@link https://developer.chrome.com/extensions/background_pages | extension background page} in Chromium.
50 *
51 * @remarks
52 *
53 * One Browser instance might have multiple Page instances.
54 *
55 * @example
56 * This example creates a page, navigates it to a URL, and then * saves a screenshot:
57 * ```js
58 * const puppeteer = require('puppeteer');
59 *
60 * (async () => {
61 *   const browser = await puppeteer.launch();
62 *   const page = await browser.newPage();
63 *   await page.goto('https://example.com');
64 *   await page.screenshot({path: 'screenshot.png'});
65 *   await browser.close();
66 * })();
67 * ```
68 *
69 * The Page class extends from Puppeteer's {@link EventEmitter} class and will
70 * emit various events which are documented in the {@link PageEmittedEvents} enum.
71 *
72 * @example
73 * This example logs a message for a single page `load` event:
74 * ```js
75 * page.once('load', () => console.log('Page loaded!'));
76 * ```
77 *
78 * To unsubscribe from events use the `off` method:
79 *
80 * ```js
81 * function logRequest(interceptedRequest) {
82 *   console.log('A request was made:', interceptedRequest.url());
83 * }
84 * page.on('request', logRequest);
85 * // Sometime later...
86 * page.off('request', logRequest);
87 * ```
88 * @public
89 */
90export class Page extends EventEmitter {
91    /**
92     * @internal
93     */
94    constructor(client, target, ignoreHTTPSErrors) {
95        super();
96        this._closed = false;
97        this._timeoutSettings = new TimeoutSettings();
98        this._pageBindings = new Map();
99        this._javascriptEnabled = true;
100        this._workers = new Map();
101        // TODO: improve this typedef - it's a function that takes a file chooser or
102        // something?
103        this._fileChooserInterceptors = new Set();
104        this._client = client;
105        this._target = target;
106        this._keyboard = new Keyboard(client);
107        this._mouse = new Mouse(client, this._keyboard);
108        this._touchscreen = new Touchscreen(client, this._keyboard);
109        this._accessibility = new Accessibility(client);
110        this._frameManager = new FrameManager(client, this, ignoreHTTPSErrors, this._timeoutSettings);
111        this._emulationManager = new EmulationManager(client);
112        this._tracing = new Tracing(client);
113        this._coverage = new Coverage(client);
114        this._screenshotTaskQueue = new ScreenshotTaskQueue();
115        this._viewport = null;
116        client.on('Target.attachedToTarget', (event) => {
117            if (event.targetInfo.type !== 'worker') {
118                // If we don't detach from service workers, they will never die.
119                client
120                    .send('Target.detachFromTarget', {
121                    sessionId: event.sessionId,
122                })
123                    .catch(debugError);
124                return;
125            }
126            const session = Connection.fromSession(client).session(event.sessionId);
127            const worker = new WebWorker(session, event.targetInfo.url, this._addConsoleMessage.bind(this), this._handleException.bind(this));
128            this._workers.set(event.sessionId, worker);
129            this.emit("workercreated" /* WorkerCreated */, worker);
130        });
131        client.on('Target.detachedFromTarget', (event) => {
132            const worker = this._workers.get(event.sessionId);
133            if (!worker)
134                return;
135            this.emit("workerdestroyed" /* WorkerDestroyed */, worker);
136            this._workers.delete(event.sessionId);
137        });
138        this._frameManager.on(FrameManagerEmittedEvents.FrameAttached, (event) => this.emit("frameattached" /* FrameAttached */, event));
139        this._frameManager.on(FrameManagerEmittedEvents.FrameDetached, (event) => this.emit("framedetached" /* FrameDetached */, event));
140        this._frameManager.on(FrameManagerEmittedEvents.FrameNavigated, (event) => this.emit("framenavigated" /* FrameNavigated */, event));
141        const networkManager = this._frameManager.networkManager();
142        networkManager.on(NetworkManagerEmittedEvents.Request, (event) => this.emit("request" /* Request */, event));
143        networkManager.on(NetworkManagerEmittedEvents.Response, (event) => this.emit("response" /* Response */, event));
144        networkManager.on(NetworkManagerEmittedEvents.RequestFailed, (event) => this.emit("requestfailed" /* RequestFailed */, event));
145        networkManager.on(NetworkManagerEmittedEvents.RequestFinished, (event) => this.emit("requestfinished" /* RequestFinished */, event));
146        this._fileChooserInterceptors = new Set();
147        client.on('Page.domContentEventFired', () => this.emit("domcontentloaded" /* DOMContentLoaded */));
148        client.on('Page.loadEventFired', () => this.emit("load" /* Load */));
149        client.on('Runtime.consoleAPICalled', (event) => this._onConsoleAPI(event));
150        client.on('Runtime.bindingCalled', (event) => this._onBindingCalled(event));
151        client.on('Page.javascriptDialogOpening', (event) => this._onDialog(event));
152        client.on('Runtime.exceptionThrown', (exception) => this._handleException(exception.exceptionDetails));
153        client.on('Inspector.targetCrashed', () => this._onTargetCrashed());
154        client.on('Performance.metrics', (event) => this._emitMetrics(event));
155        client.on('Log.entryAdded', (event) => this._onLogEntryAdded(event));
156        client.on('Page.fileChooserOpened', (event) => this._onFileChooser(event));
157        this._target._isClosedPromise.then(() => {
158            this.emit("close" /* Close */);
159            this._closed = true;
160        });
161    }
162    /**
163     * @internal
164     */
165    static async create(client, target, ignoreHTTPSErrors, defaultViewport) {
166        const page = new Page(client, target, ignoreHTTPSErrors);
167        await page._initialize();
168        if (defaultViewport)
169            await page.setViewport(defaultViewport);
170        return page;
171    }
172    async _initialize() {
173        await Promise.all([
174            this._frameManager.initialize(),
175            this._client.send('Target.setAutoAttach', {
176                autoAttach: true,
177                waitForDebuggerOnStart: false,
178                flatten: true,
179            }),
180            this._client.send('Performance.enable'),
181            this._client.send('Log.enable'),
182        ]);
183    }
184    async _onFileChooser(event) {
185        if (!this._fileChooserInterceptors.size)
186            return;
187        const frame = this._frameManager.frame(event.frameId);
188        const context = await frame.executionContext();
189        const element = await context._adoptBackendNodeId(event.backendNodeId);
190        const interceptors = Array.from(this._fileChooserInterceptors);
191        this._fileChooserInterceptors.clear();
192        const fileChooser = new FileChooser(element, event);
193        for (const interceptor of interceptors)
194            interceptor.call(null, fileChooser);
195    }
196    /**
197     * @returns `true` if the page has JavaScript enabled, `false` otherwise.
198     */
199    isJavaScriptEnabled() {
200        return this._javascriptEnabled;
201    }
202    /**
203     * @param options - Optional waiting parameters
204     * @returns Resolves after a page requests a file picker.
205     */
206    async waitForFileChooser(options = {}) {
207        if (!this._fileChooserInterceptors.size)
208            await this._client.send('Page.setInterceptFileChooserDialog', {
209                enabled: true,
210            });
211        const { timeout = this._timeoutSettings.timeout() } = options;
212        let callback;
213        const promise = new Promise((x) => (callback = x));
214        this._fileChooserInterceptors.add(callback);
215        return helper
216            .waitWithTimeout(promise, 'waiting for file chooser', timeout)
217            .catch((error) => {
218            this._fileChooserInterceptors.delete(callback);
219            throw error;
220        });
221    }
222    /**
223     * Sets the page's geolocation.
224     *
225     * @remarks
226     * Consider using {@link BrowserContext.overridePermissions} to grant
227     * permissions for the page to read its geolocation.
228     *
229     * @example
230     * ```js
231     * await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
232     * ```
233     */
234    async setGeolocation(options) {
235        const { longitude, latitude, accuracy = 0 } = options;
236        if (longitude < -180 || longitude > 180)
237            throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
238        if (latitude < -90 || latitude > 90)
239            throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
240        if (accuracy < 0)
241            throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
242        await this._client.send('Emulation.setGeolocationOverride', {
243            longitude,
244            latitude,
245            accuracy,
246        });
247    }
248    /**
249     * @returns A target this page was created from.
250     */
251    target() {
252        return this._target;
253    }
254    /**
255     * @returns The browser this page belongs to.
256     */
257    browser() {
258        return this._target.browser();
259    }
260    /**
261     * @returns The browser context that the page belongs to
262     */
263    browserContext() {
264        return this._target.browserContext();
265    }
266    _onTargetCrashed() {
267        this.emit('error', new Error('Page crashed!'));
268    }
269    _onLogEntryAdded(event) {
270        const { level, text, args, source, url, lineNumber } = event.entry;
271        if (args)
272            args.map((arg) => helper.releaseObject(this._client, arg));
273        if (source !== 'worker')
274            this.emit("console" /* Console */, new ConsoleMessage(level, text, [], [{ url, lineNumber }]));
275    }
276    /**
277     * @returns The page's main frame.
278     */
279    mainFrame() {
280        return this._frameManager.mainFrame();
281    }
282    get keyboard() {
283        return this._keyboard;
284    }
285    get touchscreen() {
286        return this._touchscreen;
287    }
288    get coverage() {
289        return this._coverage;
290    }
291    get tracing() {
292        return this._tracing;
293    }
294    get accessibility() {
295        return this._accessibility;
296    }
297    /**
298     * @returns An array of all frames attached to the page.
299     */
300    frames() {
301        return this._frameManager.frames();
302    }
303    /**
304     * @returns all of the dedicated
305     * {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API | WebWorkers}
306     * associated with the page.
307     */
308    workers() {
309        return Array.from(this._workers.values());
310    }
311    /**
312     * @param value - Whether to enable request interception.
313     *
314     * @remarks
315     * Activating request interception enables {@link HTTPRequest.abort},
316     * {@link HTTPRequest.continue} and {@link HTTPRequest.respond} methods.  This
317     * provides the capability to modify network requests that are made by a page.
318     *
319     * Once request interception is enabled, every request will stall unless it's
320     * continued, responded or aborted.
321     *
322     * **NOTE** Enabling request interception disables page caching.
323     *
324     * @example
325     * An example of a naïve request interceptor that aborts all image requests:
326     * ```js
327     * const puppeteer = require('puppeteer');
328     * (async () => {
329     *   const browser = await puppeteer.launch();
330     *   const page = await browser.newPage();
331     *   await page.setRequestInterception(true);
332     *   page.on('request', interceptedRequest => {
333     *     if (interceptedRequest.url().endsWith('.png') ||
334     *         interceptedRequest.url().endsWith('.jpg'))
335     *       interceptedRequest.abort();
336     *     else
337     *       interceptedRequest.continue();
338     *     });
339     *   await page.goto('https://example.com');
340     *   await browser.close();
341     * })();
342     * ```
343     */
344    async setRequestInterception(value) {
345        return this._frameManager.networkManager().setRequestInterception(value);
346    }
347    /**
348     * @param enabled - When `true`, enables offline mode for the page.
349     */
350    setOfflineMode(enabled) {
351        return this._frameManager.networkManager().setOfflineMode(enabled);
352    }
353    /**
354     * @param timeout - Maximum navigation time in milliseconds.
355     */
356    setDefaultNavigationTimeout(timeout) {
357        this._timeoutSettings.setDefaultNavigationTimeout(timeout);
358    }
359    /**
360     * @param timeout - Maximum time in milliseconds.
361     */
362    setDefaultTimeout(timeout) {
363        this._timeoutSettings.setDefaultTimeout(timeout);
364    }
365    /**
366     * Runs `document.querySelector` within the page. If no element matches the
367     * selector, the return value resolves to `null`.
368     *
369     * @remarks
370     * Shortcut for {@link Frame.$ | Page.mainFrame().$(selector) }.
371     *
372     * @param selector - A
373     * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
374     * to query page for.
375     */
376    async $(selector) {
377        return this.mainFrame().$(selector);
378    }
379    /**
380     * @remarks
381     *
382     * The only difference between {@link Page.evaluate | page.evaluate} and
383     * `page.evaluateHandle` is that `evaluateHandle` will return the value
384     * wrapped in an in-page object.
385     *
386     * If the function passed to `page.evaluteHandle` returns a Promise, the
387     * function will wait for the promise to resolve and return its value.
388     *
389     * You can pass a string instead of a function (although functions are
390     * recommended as they are easier to debug and use with TypeScript):
391     *
392     * @example
393     * ```
394     * const aHandle = await page.evaluateHandle('document')
395     * ```
396     *
397     * @example
398     * {@link JSHandle} instances can be passed as arguments to the `pageFunction`:
399     * ```
400     * const aHandle = await page.evaluateHandle(() => document.body);
401     * const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
402     * console.log(await resultHandle.jsonValue());
403     * await resultHandle.dispose();
404     * ```
405     *
406     * Most of the time this function returns a {@link JSHandle},
407     * but if `pageFunction` returns a reference to an element,
408     * you instead get an {@link ElementHandle} back:
409     *
410     * @example
411     * ```
412     * const button = await page.evaluateHandle(() => document.querySelector('button'));
413     * // can call `click` because `button` is an `ElementHandle`
414     * await button.click();
415     * ```
416     *
417     * The TypeScript definitions assume that `evaluateHandle` returns
418     *  a `JSHandle`, but if you know it's going to return an
419     * `ElementHandle`, pass it as the generic argument:
420     *
421     * ```
422     * const button = await page.evaluateHandle<ElementHandle>(...);
423     * ```
424     *
425     * @param pageFunction - a function that is run within the page
426     * @param args - arguments to be passed to the pageFunction
427     */
428    async evaluateHandle(pageFunction, ...args) {
429        const context = await this.mainFrame().executionContext();
430        return context.evaluateHandle(pageFunction, ...args);
431    }
432    /**
433     * This method iterates the JavaScript heap and finds all objects with the
434     * given prototype.
435     *
436     * @remarks
437     *
438     * @example
439     *
440     * ```js
441     * // Create a Map object
442     * await page.evaluate(() => window.map = new Map());
443     * // Get a handle to the Map object prototype
444     * const mapPrototype = await page.evaluateHandle(() => Map.prototype);
445     * // Query all map instances into an array
446     * const mapInstances = await page.queryObjects(mapPrototype);
447     * // Count amount of map objects in heap
448     * const count = await page.evaluate(maps => maps.length, mapInstances);
449     * await mapInstances.dispose();
450     * await mapPrototype.dispose();
451     * ```
452     * @param prototypeHandle - a handle to the object prototype.
453     */
454    async queryObjects(prototypeHandle) {
455        const context = await this.mainFrame().executionContext();
456        return context.queryObjects(prototypeHandle);
457    }
458    /**
459     * This method runs `document.querySelector` within the page and passes the
460     * result as the first argument to the `pageFunction`.
461     *
462     * @remarks
463     *
464     * If no element is found matching `selector`, the method will throw an error.
465     *
466     * If `pageFunction` returns a promise `$eval` will wait for the promise to
467     * resolve and then return its value.
468     *
469     * @example
470     *
471     * ```
472     * const searchValue = await page.$eval('#search', el => el.value);
473     * const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
474     * const html = await page.$eval('.main-container', el => el.outerHTML);
475     * ```
476     *
477     * If you are using TypeScript, you may have to provide an explicit type to the
478     * first argument of the `pageFunction`.
479     * By default it is typed as `Element`, but you may need to provide a more
480     * specific sub-type:
481     *
482     * @example
483     *
484     * ```
485     * // if you don't provide HTMLInputElement here, TS will error
486     * // as `value` is not on `Element`
487     * const searchValue = await page.$eval('#search', (el: HTMLInputElement) => el.value);
488     * ```
489     *
490     * The compiler should be able to infer the return type
491     * from the `pageFunction` you provide. If it is unable to, you can use the generic
492     * type to tell the compiler what return type you expect from `$eval`:
493     *
494     * @example
495     *
496     * ```
497     * // The compiler can infer the return type in this case, but if it can't
498     * // or if you want to be more explicit, provide it as the generic type.
499     * const searchValue = await page.$eval<string>(
500     *  '#search', (el: HTMLInputElement) => el.value
501     * );
502     * ```
503     *
504     * @param selector - the
505     * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
506     * to query for
507     * @param pageFunction - the function to be evaluated in the page context.
508     * Will be passed the result of `document.querySelector(selector)` as its
509     * first argument.
510     * @param args - any additional arguments to pass through to `pageFunction`.
511     *
512     * @returns The result of calling `pageFunction`. If it returns an element it
513     * is wrapped in an {@link ElementHandle}, else the raw value itself is
514     * returned.
515     */
516    async $eval(selector, pageFunction, ...args) {
517        return this.mainFrame().$eval(selector, pageFunction, ...args);
518    }
519    /**
520     * This method runs `Array.from(document.querySelectorAll(selector))` within
521     * the page and passes the result as the first argument to the `pageFunction`.
522     *
523     * @remarks
524     *
525     * If `pageFunction` returns a promise `$$eval` will wait for the promise to
526     * resolve and then return its value.
527     *
528     * @example
529     *
530     * ```
531     * // get the amount of divs on the page
532     * const divCount = await page.$$eval('div', divs => divs.length);
533     *
534     * // get the text content of all the `.options` elements:
535     * const options = await page.$$eval('div > span.options', options => {
536     *   return options.map(option => option.textContent)
537     * });
538     * ```
539     *
540     * If you are using TypeScript, you may have to provide an explicit type to the
541     * first argument of the `pageFunction`.
542     * By default it is typed as `Element[]`, but you may need to provide a more
543     * specific sub-type:
544     *
545     * @example
546     *
547     * ```
548     * // if you don't provide HTMLInputElement here, TS will error
549     * // as `value` is not on `Element`
550     * await page.$$eval('input', (elements: HTMLInputElement[]) => {
551     *   return elements.map(e => e.value);
552     * });
553     * ```
554     *
555     * The compiler should be able to infer the return type
556     * from the `pageFunction` you provide. If it is unable to, you can use the generic
557     * type to tell the compiler what return type you expect from `$$eval`:
558     *
559     * @example
560     *
561     * ```
562     * // The compiler can infer the return type in this case, but if it can't
563     * // or if you want to be more explicit, provide it as the generic type.
564     * const allInputValues = await page.$$eval<string[]>(
565     *  'input', (elements: HTMLInputElement[]) => elements.map(e => e.textContent)
566     * );
567     * ```
568     *
569     * @param selector the
570     * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
571     * to query for
572     * @param pageFunction the function to be evaluated in the page context. Will
573     * be passed the result of `Array.from(document.querySelectorAll(selector))`
574     * as its first argument.
575     * @param args any additional arguments to pass through to `pageFunction`.
576     *
577     * @returns The result of calling `pageFunction`. If it returns an element it
578     * is wrapped in an {@link ElementHandle}, else the raw value itself is
579     * returned.
580     */
581    async $$eval(selector, pageFunction, ...args) {
582        return this.mainFrame().$$eval(selector, pageFunction, ...args);
583    }
584    async $$(selector) {
585        return this.mainFrame().$$(selector);
586    }
587    async $x(expression) {
588        return this.mainFrame().$x(expression);
589    }
590    /**
591     * If no URLs are specified, this method returns cookies for the current page
592     * URL. If URLs are specified, only cookies for those URLs are returned.
593     */
594    async cookies(...urls) {
595        const originalCookies = (await this._client.send('Network.getCookies', {
596            urls: urls.length ? urls : [this.url()],
597        })).cookies;
598        const unsupportedCookieAttributes = ['priority'];
599        const filterUnsupportedAttributes = (cookie) => {
600            for (const attr of unsupportedCookieAttributes)
601                delete cookie[attr];
602            return cookie;
603        };
604        return originalCookies.map(filterUnsupportedAttributes);
605    }
606    async deleteCookie(...cookies) {
607        const pageURL = this.url();
608        for (const cookie of cookies) {
609            const item = Object.assign({}, cookie);
610            if (!cookie.url && pageURL.startsWith('http'))
611                item.url = pageURL;
612            await this._client.send('Network.deleteCookies', item);
613        }
614    }
615    async setCookie(...cookies) {
616        const pageURL = this.url();
617        const startsWithHTTP = pageURL.startsWith('http');
618        const items = cookies.map((cookie) => {
619            const item = Object.assign({}, cookie);
620            if (!item.url && startsWithHTTP)
621                item.url = pageURL;
622            assert(item.url !== 'about:blank', `Blank page can not have cookie "${item.name}"`);
623            assert(!String.prototype.startsWith.call(item.url || '', 'data:'), `Data URL page can not have cookie "${item.name}"`);
624            return item;
625        });
626        await this.deleteCookie(...items);
627        if (items.length)
628            await this._client.send('Network.setCookies', { cookies: items });
629    }
630    async addScriptTag(options) {
631        return this.mainFrame().addScriptTag(options);
632    }
633    async addStyleTag(options) {
634        return this.mainFrame().addStyleTag(options);
635    }
636    async exposeFunction(name, puppeteerFunction) {
637        if (this._pageBindings.has(name))
638            throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);
639        this._pageBindings.set(name, puppeteerFunction);
640        const expression = helper.pageBindingInitString('exposedFun', name);
641        await this._client.send('Runtime.addBinding', { name: name });
642        await this._client.send('Page.addScriptToEvaluateOnNewDocument', {
643            source: expression,
644        });
645        await Promise.all(this.frames().map((frame) => frame.evaluate(expression).catch(debugError)));
646    }
647    async authenticate(credentials) {
648        return this._frameManager.networkManager().authenticate(credentials);
649    }
650    async setExtraHTTPHeaders(headers) {
651        return this._frameManager.networkManager().setExtraHTTPHeaders(headers);
652    }
653    async setUserAgent(userAgent) {
654        return this._frameManager.networkManager().setUserAgent(userAgent);
655    }
656    async metrics() {
657        const response = await this._client.send('Performance.getMetrics');
658        return this._buildMetricsObject(response.metrics);
659    }
660    _emitMetrics(event) {
661        this.emit("metrics" /* Metrics */, {
662            title: event.title,
663            metrics: this._buildMetricsObject(event.metrics),
664        });
665    }
666    _buildMetricsObject(metrics) {
667        const result = {};
668        for (const metric of metrics || []) {
669            if (supportedMetrics.has(metric.name))
670                result[metric.name] = metric.value;
671        }
672        return result;
673    }
674    _handleException(exceptionDetails) {
675        const message = helper.getExceptionMessage(exceptionDetails);
676        const err = new Error(message);
677        err.stack = ''; // Don't report clientside error with a node stack attached
678        this.emit("pageerror" /* PageError */, err);
679    }
680    async _onConsoleAPI(event) {
681        if (event.executionContextId === 0) {
682            // DevTools protocol stores the last 1000 console messages. These
683            // messages are always reported even for removed execution contexts. In
684            // this case, they are marked with executionContextId = 0 and are
685            // reported upon enabling Runtime agent.
686            //
687            // Ignore these messages since:
688            // - there's no execution context we can use to operate with message
689            //   arguments
690            // - these messages are reported before Puppeteer clients can subscribe
691            //   to the 'console'
692            //   page event.
693            //
694            // @see https://github.com/puppeteer/puppeteer/issues/3865
695            return;
696        }
697        const context = this._frameManager.executionContextById(event.executionContextId);
698        const values = event.args.map((arg) => createJSHandle(context, arg));
699        this._addConsoleMessage(event.type, values, event.stackTrace);
700    }
701    async _onBindingCalled(event) {
702        let payload;
703        try {
704            payload = JSON.parse(event.payload);
705        }
706        catch {
707            // The binding was either called by something in the page or it was
708            // called before our wrapper was initialized.
709            return;
710        }
711        const { type, name, seq, args } = payload;
712        if (type !== 'exposedFun' || !this._pageBindings.has(name))
713            return;
714        let expression = null;
715        try {
716            const result = await this._pageBindings.get(name)(...args);
717            expression = helper.pageBindingDeliverResultString(name, seq, result);
718        }
719        catch (error) {
720            if (error instanceof Error)
721                expression = helper.pageBindingDeliverErrorString(name, seq, error.message, error.stack);
722            else
723                expression = helper.pageBindingDeliverErrorValueString(name, seq, error);
724        }
725        this._client
726            .send('Runtime.evaluate', {
727            expression,
728            contextId: event.executionContextId,
729        })
730            .catch(debugError);
731    }
732    _addConsoleMessage(type, args, stackTrace) {
733        if (!this.listenerCount("console" /* Console */)) {
734            args.forEach((arg) => arg.dispose());
735            return;
736        }
737        const textTokens = [];
738        for (const arg of args) {
739            const remoteObject = arg._remoteObject;
740            if (remoteObject.objectId)
741                textTokens.push(arg.toString());
742            else
743                textTokens.push(helper.valueFromRemoteObject(remoteObject));
744        }
745        const stackTraceLocations = [];
746        if (stackTrace) {
747            for (const callFrame of stackTrace.callFrames) {
748                stackTraceLocations.push({
749                    url: callFrame.url,
750                    lineNumber: callFrame.lineNumber,
751                    columnNumber: callFrame.columnNumber,
752                });
753            }
754        }
755        const message = new ConsoleMessage(type, textTokens.join(' '), args, stackTraceLocations);
756        this.emit("console" /* Console */, message);
757    }
758    _onDialog(event) {
759        let dialogType = null;
760        const validDialogTypes = new Set([
761            'alert',
762            'confirm',
763            'prompt',
764            'beforeunload',
765        ]);
766        if (validDialogTypes.has(event.type)) {
767            dialogType = event.type;
768        }
769        assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
770        const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt);
771        this.emit("dialog" /* Dialog */, dialog);
772    }
773    url() {
774        return this.mainFrame().url();
775    }
776    async content() {
777        return await this._frameManager.mainFrame().content();
778    }
779    async setContent(html, options = {}) {
780        await this._frameManager.mainFrame().setContent(html, options);
781    }
782    async goto(url, options = {}) {
783        return await this._frameManager.mainFrame().goto(url, options);
784    }
785    async reload(options) {
786        const result = await Promise.all([
787            this.waitForNavigation(options),
788            this._client.send('Page.reload'),
789        ]);
790        return result[0];
791    }
792    async waitForNavigation(options = {}) {
793        return await this._frameManager.mainFrame().waitForNavigation(options);
794    }
795    _sessionClosePromise() {
796        if (!this._disconnectPromise)
797            this._disconnectPromise = new Promise((fulfill) => this._client.once(CDPSessionEmittedEvents.Disconnected, () => fulfill(new Error('Target closed'))));
798        return this._disconnectPromise;
799    }
800    async waitForRequest(urlOrPredicate, options = {}) {
801        const { timeout = this._timeoutSettings.timeout() } = options;
802        return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEmittedEvents.Request, (request) => {
803            if (helper.isString(urlOrPredicate))
804                return urlOrPredicate === request.url();
805            if (typeof urlOrPredicate === 'function')
806                return !!urlOrPredicate(request);
807            return false;
808        }, timeout, this._sessionClosePromise());
809    }
810    async waitForResponse(urlOrPredicate, options = {}) {
811        const { timeout = this._timeoutSettings.timeout() } = options;
812        return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEmittedEvents.Response, (response) => {
813            if (helper.isString(urlOrPredicate))
814                return urlOrPredicate === response.url();
815            if (typeof urlOrPredicate === 'function')
816                return !!urlOrPredicate(response);
817            return false;
818        }, timeout, this._sessionClosePromise());
819    }
820    async goBack(options = {}) {
821        return this._go(-1, options);
822    }
823    async goForward(options = {}) {
824        return this._go(+1, options);
825    }
826    async _go(delta, options) {
827        const history = await this._client.send('Page.getNavigationHistory');
828        const entry = history.entries[history.currentIndex + delta];
829        if (!entry)
830            return null;
831        const result = await Promise.all([
832            this.waitForNavigation(options),
833            this._client.send('Page.navigateToHistoryEntry', { entryId: entry.id }),
834        ]);
835        return result[0];
836    }
837    async bringToFront() {
838        await this._client.send('Page.bringToFront');
839    }
840    async emulate(options) {
841        await Promise.all([
842            this.setViewport(options.viewport),
843            this.setUserAgent(options.userAgent),
844        ]);
845    }
846    async setJavaScriptEnabled(enabled) {
847        if (this._javascriptEnabled === enabled)
848            return;
849        this._javascriptEnabled = enabled;
850        await this._client.send('Emulation.setScriptExecutionDisabled', {
851            value: !enabled,
852        });
853    }
854    async setBypassCSP(enabled) {
855        await this._client.send('Page.setBypassCSP', { enabled });
856    }
857    async emulateMediaType(type) {
858        assert(type === 'screen' || type === 'print' || type === null, 'Unsupported media type: ' + type);
859        await this._client.send('Emulation.setEmulatedMedia', {
860            media: type || '',
861        });
862    }
863    async emulateMediaFeatures(features) {
864        if (features === null)
865            await this._client.send('Emulation.setEmulatedMedia', { features: null });
866        if (Array.isArray(features)) {
867            features.every((mediaFeature) => {
868                const name = mediaFeature.name;
869                assert(/^prefers-(?:color-scheme|reduced-motion)$/.test(name), 'Unsupported media feature: ' + name);
870                return true;
871            });
872            await this._client.send('Emulation.setEmulatedMedia', {
873                features: features,
874            });
875        }
876    }
877    async emulateTimezone(timezoneId) {
878        try {
879            await this._client.send('Emulation.setTimezoneOverride', {
880                timezoneId: timezoneId || '',
881            });
882        }
883        catch (error) {
884            if (error.message.includes('Invalid timezone'))
885                throw new Error(`Invalid timezone ID: ${timezoneId}`);
886            throw error;
887        }
888    }
889    /**
890     * Emulates the idle state.
891     * If no arguments set, clears idle state emulation.
892     *
893     * @example
894     * ```js
895     * // set idle emulation
896     * await page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});
897     *
898     * // do some checks here
899     * ...
900     *
901     * // clear idle emulation
902     * await page.emulateIdleState();
903     * ```
904     *
905     * @param overrides Mock idle state. If not set, clears idle overrides
906     * @param isUserActive Mock isUserActive
907     * @param isScreenUnlocked Mock isScreenUnlocked
908     */
909    async emulateIdleState(overrides) {
910        if (overrides) {
911            await this._client.send('Emulation.setIdleOverride', {
912                isUserActive: overrides.isUserActive,
913                isScreenUnlocked: overrides.isScreenUnlocked,
914            });
915        }
916        else {
917            await this._client.send('Emulation.clearIdleOverride');
918        }
919    }
920    /**
921     * Simulates the given vision deficiency on the page.
922     *
923     * @example
924     * ```js
925     * const puppeteer = require('puppeteer');
926     *
927     * (async () => {
928     *   const browser = await puppeteer.launch();
929     *   const page = await browser.newPage();
930     *   await page.goto('https://v8.dev/blog/10-years');
931     *
932     *   await page.emulateVisionDeficiency('achromatopsia');
933     *   await page.screenshot({ path: 'achromatopsia.png' });
934     *
935     *   await page.emulateVisionDeficiency('deuteranopia');
936     *   await page.screenshot({ path: 'deuteranopia.png' });
937     *
938     *   await page.emulateVisionDeficiency('blurredVision');
939     *   await page.screenshot({ path: 'blurred-vision.png' });
940     *
941     *   await browser.close();
942     * })();
943     * ```
944     *
945     * @param type - the type of deficiency to simulate, or `'none'` to reset.
946     */
947    async emulateVisionDeficiency(type) {
948        const visionDeficiencies = new Set([
949            'none',
950            'achromatopsia',
951            'blurredVision',
952            'deuteranopia',
953            'protanopia',
954            'tritanopia',
955        ]);
956        try {
957            assert(!type || visionDeficiencies.has(type), `Unsupported vision deficiency: ${type}`);
958            await this._client.send('Emulation.setEmulatedVisionDeficiency', {
959                type: type || 'none',
960            });
961        }
962        catch (error) {
963            throw error;
964        }
965    }
966    async setViewport(viewport) {
967        const needsReload = await this._emulationManager.emulateViewport(viewport);
968        this._viewport = viewport;
969        if (needsReload)
970            await this.reload();
971    }
972    viewport() {
973        return this._viewport;
974    }
975    /**
976     * @remarks
977     *
978     * Evaluates a function in the page's context and returns the result.
979     *
980     * If the function passed to `page.evaluteHandle` returns a Promise, the
981     * function will wait for the promise to resolve and return its value.
982     *
983     * @example
984     *
985     * ```js
986     * const result = await frame.evaluate(() => {
987     *   return Promise.resolve(8 * 7);
988     * });
989     * console.log(result); // prints "56"
990     * ```
991     *
992     * You can pass a string instead of a function (although functions are
993     * recommended as they are easier to debug and use with TypeScript):
994     *
995     * @example
996     * ```
997     * const aHandle = await page.evaluate('1 + 2');
998     * ```
999     *
1000     * To get the best TypeScript experience, you should pass in as the
1001     * generic the type of `pageFunction`:
1002     *
1003     * ```
1004     * const aHandle = await page.evaluate<() => number>(() => 2);
1005     * ```
1006     *
1007     * @example
1008     *
1009     * {@link ElementHandle} instances (including {@link JSHandle}s) can be passed
1010     * as arguments to the `pageFunction`:
1011     *
1012     * ```
1013     * const bodyHandle = await page.$('body');
1014     * const html = await page.evaluate(body => body.innerHTML, bodyHandle);
1015     * await bodyHandle.dispose();
1016     * ```
1017     *
1018     * @param pageFunction - a function that is run within the page
1019     * @param args - arguments to be passed to the pageFunction
1020     *
1021     * @returns the return value of `pageFunction`.
1022     */
1023    async evaluate(pageFunction, ...args) {
1024        return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
1025    }
1026    async evaluateOnNewDocument(pageFunction, ...args) {
1027        const source = helper.evaluationString(pageFunction, ...args);
1028        await this._client.send('Page.addScriptToEvaluateOnNewDocument', {
1029            source,
1030        });
1031    }
1032    async setCacheEnabled(enabled = true) {
1033        await this._frameManager.networkManager().setCacheEnabled(enabled);
1034    }
1035    async screenshot(options = {}) {
1036        let screenshotType = null;
1037        // options.type takes precedence over inferring the type from options.path
1038        // because it may be a 0-length file with no extension created beforehand
1039        // (i.e. as a temp file).
1040        if (options.type) {
1041            assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type);
1042            screenshotType = options.type;
1043        }
1044        else if (options.path) {
1045            const filePath = options.path;
1046            const extension = filePath
1047                .slice(filePath.lastIndexOf('.') + 1)
1048                .toLowerCase();
1049            if (extension === 'png')
1050                screenshotType = 'png';
1051            else if (extension === 'jpg' || extension === 'jpeg')
1052                screenshotType = 'jpeg';
1053            assert(screenshotType, `Unsupported screenshot type for extension \`.${extension}\``);
1054        }
1055        if (!screenshotType)
1056            screenshotType = 'png';
1057        if (options.quality) {
1058            assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' +
1059                screenshotType +
1060                ' screenshots');
1061            assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' +
1062                typeof options.quality);
1063            assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');
1064            assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' +