isomorfeus-puppetmaster 0.5.2 → 0.5.6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (836) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +12 -17
  3. data/lib/isomorfeus/puppetmaster/console_message.rb +18 -18
  4. data/lib/isomorfeus/puppetmaster/cookie.rb +46 -46
  5. data/lib/isomorfeus/puppetmaster/driver/puppeteer.rb +413 -403
  6. data/lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb +953 -953
  7. data/lib/isomorfeus/puppetmaster/driver/puppeteer_node.rb +851 -851
  8. data/lib/isomorfeus/puppetmaster/errors.rb +90 -90
  9. data/lib/isomorfeus/puppetmaster/iframe.rb +16 -16
  10. data/lib/isomorfeus/puppetmaster/node/content_editable.rb +17 -17
  11. data/lib/isomorfeus/puppetmaster/node/input.rb +20 -20
  12. data/lib/isomorfeus/puppetmaster/node/select.rb +35 -35
  13. data/lib/isomorfeus/puppetmaster/node.rb +279 -279
  14. data/lib/isomorfeus/puppetmaster/request.rb +16 -16
  15. data/lib/isomorfeus/puppetmaster/response.rb +25 -25
  16. data/lib/isomorfeus/puppetmaster/self_forwardable.rb +38 -38
  17. data/lib/isomorfeus/puppetmaster/server.rb +1 -1
  18. data/lib/isomorfeus/puppetmaster/version.rb +3 -3
  19. data/lib/isomorfeus/puppetmaster.rb +85 -85
  20. data/lib/isomorfeus-puppetmaster.rb +1 -0
  21. data/node_modules/.bin/extract-zip +12 -12
  22. data/node_modules/.bin/extract-zip.ps1 +28 -28
  23. data/node_modules/.bin/rimraf +12 -12
  24. data/node_modules/.bin/rimraf.ps1 +28 -28
  25. data/node_modules/.package-lock.json +530 -574
  26. data/node_modules/@types/node/LICENSE +21 -21
  27. data/node_modules/@types/node/assert/strict.d.ts +8 -8
  28. data/node_modules/@types/node/assert.d.ts +912 -912
  29. data/node_modules/@types/node/async_hooks.d.ts +497 -497
  30. data/node_modules/@types/node/buffer.d.ts +2142 -2142
  31. data/node_modules/@types/node/child_process.d.ts +1355 -1355
  32. data/node_modules/@types/node/cluster.d.ts +414 -414
  33. data/node_modules/@types/node/console.d.ts +407 -407
  34. data/node_modules/@types/node/constants.d.ts +18 -18
  35. data/node_modules/@types/node/crypto.d.ts +3224 -3224
  36. data/node_modules/@types/node/dgram.d.ts +545 -545
  37. data/node_modules/@types/node/diagnostics_channel.d.ts +128 -128
  38. data/node_modules/@types/node/dns/promises.d.ts +357 -357
  39. data/node_modules/@types/node/dns.d.ts +643 -643
  40. data/node_modules/@types/node/domain.d.ts +169 -169
  41. data/node_modules/@types/node/events.d.ts +623 -623
  42. data/node_modules/@types/node/fs/promises.d.ts +997 -997
  43. data/node_modules/@types/node/fs.d.ts +3723 -3723
  44. data/node_modules/@types/node/globals.d.ts +285 -285
  45. data/node_modules/@types/node/globals.global.d.ts +1 -1
  46. data/node_modules/@types/node/http.d.ts +1358 -1358
  47. data/node_modules/@types/node/http2.d.ts +2100 -2100
  48. data/node_modules/@types/node/https.d.ts +391 -391
  49. data/node_modules/@types/node/index.d.ts +131 -131
  50. data/node_modules/@types/node/inspector.d.ts +2738 -2738
  51. data/node_modules/@types/node/module.d.ts +114 -114
  52. data/node_modules/@types/node/net.d.ts +783 -783
  53. data/node_modules/@types/node/os.d.ts +455 -455
  54. data/node_modules/@types/node/package.json +229 -229
  55. data/node_modules/@types/node/path.d.ts +172 -172
  56. data/node_modules/@types/node/perf_hooks.d.ts +555 -555
  57. data/node_modules/@types/node/process.d.ts +1477 -1477
  58. data/node_modules/@types/node/punycode.d.ts +117 -117
  59. data/node_modules/@types/node/querystring.d.ts +131 -131
  60. data/node_modules/@types/node/readline.d.ts +542 -542
  61. data/node_modules/@types/node/repl.d.ts +424 -424
  62. data/node_modules/@types/node/stream/consumers.d.ts +24 -24
  63. data/node_modules/@types/node/stream/promises.d.ts +42 -42
  64. data/node_modules/@types/node/stream/web.d.ts +6 -6
  65. data/node_modules/@types/node/stream.d.ts +1181 -1181
  66. data/node_modules/@types/node/string_decoder.d.ts +67 -67
  67. data/node_modules/@types/node/timers/promises.d.ts +68 -68
  68. data/node_modules/@types/node/timers.d.ts +94 -94
  69. data/node_modules/@types/node/tls.d.ts +1019 -1019
  70. data/node_modules/@types/node/trace_events.d.ts +161 -161
  71. data/node_modules/@types/node/tty.d.ts +206 -206
  72. data/node_modules/@types/node/url.d.ts +798 -798
  73. data/node_modules/@types/node/util.d.ts +1556 -1556
  74. data/node_modules/@types/node/v8.d.ts +378 -378
  75. data/node_modules/@types/node/vm.d.ts +504 -504
  76. data/node_modules/@types/node/wasi.d.ts +153 -153
  77. data/node_modules/@types/node/worker_threads.d.ts +649 -649
  78. data/node_modules/@types/node/zlib.d.ts +517 -517
  79. data/node_modules/@types/yauzl/LICENSE +21 -21
  80. data/node_modules/@types/yauzl/index.d.ts +98 -98
  81. data/node_modules/@types/yauzl/package.json +26 -26
  82. data/node_modules/agent-base/README.md +145 -145
  83. data/node_modules/agent-base/dist/src/index.d.ts +78 -78
  84. data/node_modules/agent-base/dist/src/index.js +202 -202
  85. data/node_modules/agent-base/dist/src/promisify.d.ts +4 -4
  86. data/node_modules/agent-base/dist/src/promisify.js +17 -17
  87. data/node_modules/agent-base/package.json +64 -64
  88. data/node_modules/agent-base/src/index.ts +345 -345
  89. data/node_modules/agent-base/src/promisify.ts +33 -33
  90. data/node_modules/balanced-match/.github/FUNDING.yml +2 -2
  91. data/node_modules/balanced-match/LICENSE.md +21 -21
  92. data/node_modules/balanced-match/README.md +97 -97
  93. data/node_modules/balanced-match/index.js +62 -62
  94. data/node_modules/balanced-match/package.json +48 -48
  95. data/node_modules/base64-js/LICENSE +21 -21
  96. data/node_modules/base64-js/README.md +34 -34
  97. data/node_modules/base64-js/index.d.ts +3 -3
  98. data/node_modules/base64-js/index.js +150 -150
  99. data/node_modules/base64-js/package.json +47 -47
  100. data/node_modules/bl/.travis.yml +17 -17
  101. data/node_modules/bl/BufferList.js +396 -396
  102. data/node_modules/bl/LICENSE.md +13 -13
  103. data/node_modules/bl/README.md +247 -247
  104. data/node_modules/bl/bl.js +84 -84
  105. data/node_modules/bl/package.json +37 -37
  106. data/node_modules/bl/test/convert.js +21 -21
  107. data/node_modules/bl/test/indexOf.js +492 -492
  108. data/node_modules/bl/test/isBufferList.js +32 -32
  109. data/node_modules/bl/test/test.js +869 -869
  110. data/node_modules/brace-expansion/LICENSE +21 -21
  111. data/node_modules/brace-expansion/README.md +129 -129
  112. data/node_modules/brace-expansion/index.js +201 -201
  113. data/node_modules/brace-expansion/package.json +47 -47
  114. data/node_modules/buffer/AUTHORS.md +70 -70
  115. data/node_modules/buffer/LICENSE +21 -21
  116. data/node_modules/buffer/README.md +410 -410
  117. data/node_modules/buffer/index.d.ts +186 -186
  118. data/node_modules/buffer/index.js +1817 -1817
  119. data/node_modules/buffer/package.json +96 -96
  120. data/node_modules/buffer-crc32/LICENSE +19 -19
  121. data/node_modules/buffer-crc32/README.md +47 -47
  122. data/node_modules/buffer-crc32/index.js +111 -111
  123. data/node_modules/buffer-crc32/package.json +39 -39
  124. data/node_modules/chownr/LICENSE +15 -15
  125. data/node_modules/chownr/README.md +3 -3
  126. data/node_modules/chownr/chownr.js +167 -167
  127. data/node_modules/chownr/package.json +29 -29
  128. data/node_modules/concat-map/.travis.yml +4 -4
  129. data/node_modules/concat-map/LICENSE +18 -18
  130. data/node_modules/concat-map/README.markdown +62 -62
  131. data/node_modules/concat-map/example/map.js +6 -6
  132. data/node_modules/concat-map/index.js +13 -13
  133. data/node_modules/concat-map/package.json +43 -43
  134. data/node_modules/concat-map/test/map.js +39 -39
  135. data/node_modules/debug/LICENSE +19 -19
  136. data/node_modules/debug/README.md +455 -455
  137. data/node_modules/debug/package.json +59 -59
  138. data/node_modules/debug/src/browser.js +269 -269
  139. data/node_modules/debug/src/common.js +274 -261
  140. data/node_modules/debug/src/index.js +10 -10
  141. data/node_modules/debug/src/node.js +263 -263
  142. data/node_modules/devtools-protocol/LICENSE +27 -27
  143. data/node_modules/devtools-protocol/README.md +12 -12
  144. data/node_modules/devtools-protocol/json/browser_protocol.json +20985 -20640
  145. data/node_modules/devtools-protocol/json/js_protocol.json +3531 -3580
  146. data/node_modules/devtools-protocol/package.json +17 -18
  147. data/node_modules/devtools-protocol/pdl/browser_protocol.pdl +9849 -9637
  148. data/node_modules/devtools-protocol/pdl/js_protocol.pdl +1653 -1678
  149. data/node_modules/devtools-protocol/types/protocol-mapping.d.ts +4333 -4321
  150. data/node_modules/devtools-protocol/types/protocol-proxy-api.d.ts +3695 -3683
  151. data/node_modules/devtools-protocol/types/protocol.d.ts +15714 -15538
  152. data/node_modules/end-of-stream/LICENSE +20 -20
  153. data/node_modules/end-of-stream/README.md +54 -54
  154. data/node_modules/end-of-stream/index.js +94 -94
  155. data/node_modules/end-of-stream/package.json +37 -37
  156. data/node_modules/extract-zip/LICENSE +23 -23
  157. data/node_modules/extract-zip/cli.js +19 -19
  158. data/node_modules/extract-zip/index.d.ts +21 -21
  159. data/node_modules/extract-zip/index.js +173 -173
  160. data/node_modules/extract-zip/package.json +80 -80
  161. data/node_modules/extract-zip/readme.md +57 -57
  162. data/node_modules/fd-slicer/.npmignore +2 -2
  163. data/node_modules/fd-slicer/.travis.yml +7 -7
  164. data/node_modules/fd-slicer/CHANGELOG.md +49 -49
  165. data/node_modules/fd-slicer/LICENSE +21 -21
  166. data/node_modules/fd-slicer/README.md +199 -199
  167. data/node_modules/fd-slicer/index.js +296 -296
  168. data/node_modules/fd-slicer/package.json +36 -36
  169. data/node_modules/fd-slicer/test/test.js +350 -350
  170. data/node_modules/find-up/index.d.ts +137 -137
  171. data/node_modules/find-up/index.js +89 -89
  172. data/node_modules/find-up/license +9 -9
  173. data/node_modules/find-up/package.json +53 -53
  174. data/node_modules/find-up/readme.md +156 -156
  175. data/node_modules/fs-constants/LICENSE +21 -21
  176. data/node_modules/fs-constants/README.md +26 -26
  177. data/node_modules/fs-constants/browser.js +1 -1
  178. data/node_modules/fs-constants/index.js +1 -1
  179. data/node_modules/fs-constants/package.json +19 -19
  180. data/node_modules/fs.realpath/LICENSE +43 -43
  181. data/node_modules/fs.realpath/README.md +33 -33
  182. data/node_modules/fs.realpath/index.js +66 -66
  183. data/node_modules/fs.realpath/old.js +303 -303
  184. data/node_modules/fs.realpath/package.json +26 -26
  185. data/node_modules/get-stream/buffer-stream.js +52 -52
  186. data/node_modules/get-stream/index.d.ts +108 -108
  187. data/node_modules/get-stream/index.js +60 -60
  188. data/node_modules/get-stream/license +9 -9
  189. data/node_modules/get-stream/package.json +50 -50
  190. data/node_modules/get-stream/readme.md +124 -124
  191. data/node_modules/glob/LICENSE +21 -21
  192. data/node_modules/glob/README.md +375 -375
  193. data/node_modules/glob/changelog.md +67 -67
  194. data/node_modules/glob/common.js +234 -234
  195. data/node_modules/glob/glob.js +788 -788
  196. data/node_modules/glob/package.json +51 -51
  197. data/node_modules/glob/sync.js +484 -484
  198. data/node_modules/https-proxy-agent/README.md +137 -137
  199. data/node_modules/https-proxy-agent/dist/agent.d.ts +30 -30
  200. data/node_modules/https-proxy-agent/dist/agent.js +179 -179
  201. data/node_modules/https-proxy-agent/dist/index.d.ts +23 -23
  202. data/node_modules/https-proxy-agent/dist/index.js +13 -13
  203. data/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts +7 -7
  204. data/node_modules/https-proxy-agent/dist/parse-proxy-response.js +65 -65
  205. data/node_modules/https-proxy-agent/package.json +56 -56
  206. data/node_modules/ieee754/LICENSE +11 -11
  207. data/node_modules/ieee754/README.md +51 -51
  208. data/node_modules/ieee754/index.d.ts +9 -9
  209. data/node_modules/ieee754/index.js +85 -85
  210. data/node_modules/ieee754/package.json +52 -52
  211. data/node_modules/inflight/LICENSE +15 -15
  212. data/node_modules/inflight/README.md +37 -37
  213. data/node_modules/inflight/inflight.js +54 -54
  214. data/node_modules/inflight/package.json +29 -29
  215. data/node_modules/inherits/LICENSE +16 -16
  216. data/node_modules/inherits/README.md +42 -42
  217. data/node_modules/inherits/inherits.js +9 -9
  218. data/node_modules/inherits/inherits_browser.js +27 -27
  219. data/node_modules/inherits/package.json +29 -29
  220. data/node_modules/locate-path/index.d.ts +83 -83
  221. data/node_modules/locate-path/index.js +65 -65
  222. data/node_modules/locate-path/license +9 -9
  223. data/node_modules/locate-path/package.json +45 -45
  224. data/node_modules/locate-path/readme.md +122 -122
  225. data/node_modules/minimatch/LICENSE +15 -15
  226. data/node_modules/minimatch/README.md +209 -209
  227. data/node_modules/minimatch/minimatch.js +923 -923
  228. data/node_modules/minimatch/package.json +30 -30
  229. data/node_modules/{mkdirp → mkdirp-classic}/LICENSE +21 -21
  230. data/node_modules/mkdirp-classic/README.md +18 -0
  231. data/node_modules/{mkdirp → mkdirp-classic}/index.js +98 -99
  232. data/node_modules/mkdirp-classic/package.json +18 -0
  233. data/node_modules/ms/index.js +162 -162
  234. data/node_modules/ms/license.md +21 -21
  235. data/node_modules/ms/package.json +37 -37
  236. data/node_modules/ms/readme.md +60 -60
  237. data/node_modules/node-fetch/LICENSE.md +22 -22
  238. data/node_modules/node-fetch/README.md +590 -590
  239. data/node_modules/node-fetch/browser.js +24 -24
  240. data/node_modules/node-fetch/lib/index.es.js +1662 -1640
  241. data/node_modules/node-fetch/lib/index.js +1671 -1649
  242. data/node_modules/node-fetch/lib/index.mjs +1660 -1638
  243. data/node_modules/node-fetch/package.json +68 -66
  244. data/node_modules/once/LICENSE +15 -15
  245. data/node_modules/once/README.md +79 -79
  246. data/node_modules/once/once.js +42 -42
  247. data/node_modules/once/package.json +33 -33
  248. data/node_modules/p-limit/index.d.ts +38 -38
  249. data/node_modules/p-limit/index.js +57 -57
  250. data/node_modules/p-limit/license +9 -9
  251. data/node_modules/p-limit/package.json +52 -52
  252. data/node_modules/p-limit/readme.md +101 -101
  253. data/node_modules/p-locate/index.d.ts +64 -64
  254. data/node_modules/p-locate/index.js +52 -52
  255. data/node_modules/p-locate/license +9 -9
  256. data/node_modules/p-locate/package.json +53 -53
  257. data/node_modules/p-locate/readme.md +90 -90
  258. data/node_modules/p-try/index.d.ts +39 -39
  259. data/node_modules/p-try/index.js +9 -9
  260. data/node_modules/p-try/license +9 -9
  261. data/node_modules/p-try/package.json +42 -42
  262. data/node_modules/p-try/readme.md +58 -58
  263. data/node_modules/path-exists/index.d.ts +28 -28
  264. data/node_modules/path-exists/index.js +23 -23
  265. data/node_modules/path-exists/license +9 -9
  266. data/node_modules/path-exists/package.json +39 -39
  267. data/node_modules/path-exists/readme.md +52 -52
  268. data/node_modules/path-is-absolute/index.js +20 -20
  269. data/node_modules/path-is-absolute/license +21 -21
  270. data/node_modules/path-is-absolute/package.json +43 -43
  271. data/node_modules/path-is-absolute/readme.md +59 -59
  272. data/node_modules/pend/LICENSE +23 -23
  273. data/node_modules/pend/README.md +41 -41
  274. data/node_modules/pend/index.js +55 -55
  275. data/node_modules/pend/package.json +18 -18
  276. data/node_modules/pend/test.js +137 -137
  277. data/node_modules/pkg-dir/index.d.ts +44 -44
  278. data/node_modules/pkg-dir/index.js +17 -17
  279. data/node_modules/pkg-dir/license +9 -9
  280. data/node_modules/pkg-dir/package.json +56 -56
  281. data/node_modules/pkg-dir/readme.md +66 -66
  282. data/node_modules/progress/CHANGELOG.md +115 -115
  283. data/node_modules/progress/LICENSE +22 -22
  284. data/node_modules/progress/Makefile +8 -8
  285. data/node_modules/progress/Readme.md +146 -146
  286. data/node_modules/progress/index.js +1 -1
  287. data/node_modules/progress/lib/node-progress.js +236 -235
  288. data/node_modules/progress/package.json +26 -26
  289. data/node_modules/proxy-from-env/.eslintrc +29 -29
  290. data/node_modules/proxy-from-env/.travis.yml +10 -10
  291. data/node_modules/proxy-from-env/LICENSE +20 -20
  292. data/node_modules/proxy-from-env/README.md +131 -131
  293. data/node_modules/proxy-from-env/index.js +108 -108
  294. data/node_modules/proxy-from-env/package.json +34 -34
  295. data/node_modules/proxy-from-env/test.js +483 -483
  296. data/node_modules/pump/.travis.yml +5 -5
  297. data/node_modules/pump/LICENSE +20 -20
  298. data/node_modules/pump/README.md +65 -65
  299. data/node_modules/pump/index.js +82 -82
  300. data/node_modules/pump/package.json +24 -24
  301. data/node_modules/pump/test-browser.js +66 -66
  302. data/node_modules/pump/test-node.js +53 -53
  303. data/node_modules/puppeteer-core/CHANGELOG.md +319 -226
  304. data/node_modules/puppeteer-core/LICENSE +202 -202
  305. data/node_modules/puppeteer-core/README.md +481 -483
  306. data/node_modules/puppeteer-core/cjs-entry-core.js +29 -29
  307. data/node_modules/puppeteer-core/cjs-entry.js +29 -29
  308. data/node_modules/puppeteer-core/install.js +89 -89
  309. data/node_modules/puppeteer-core/lib/cjs/puppeteer/api-docs-entry.d.ts +110 -110
  310. data/node_modules/puppeteer-core/lib/cjs/puppeteer/api-docs-entry.js +80 -80
  311. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Accessibility.d.ts +175 -175
  312. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Accessibility.js +360 -360
  313. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.d.ts +20 -20
  314. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.d.ts.map +1 -1
  315. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.js +84 -84
  316. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.js.map +1 -1
  317. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Browser.d.ts +455 -437
  318. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Browser.d.ts.map +1 -1
  319. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Browser.js +540 -527
  320. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Browser.js.map +1 -1
  321. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserConnector.d.ts +53 -53
  322. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserConnector.js +97 -97
  323. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserConnector.js.map +1 -1
  324. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserWebSocketTransport.d.ts +25 -25
  325. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserWebSocketTransport.js +34 -34
  326. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.d.ts +135 -129
  327. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.d.ts.map +1 -1
  328. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.js +298 -280
  329. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.js.map +1 -1
  330. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConnectionTransport.d.ts +24 -24
  331. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConnectionTransport.js +17 -17
  332. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConsoleMessage.d.ts +72 -72
  333. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConsoleMessage.js +64 -64
  334. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Coverage.d.ts +204 -188
  335. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Coverage.d.ts.map +1 -1
  336. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Coverage.js +335 -328
  337. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Coverage.js.map +1 -1
  338. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DOMWorld.d.ts +175 -172
  339. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DOMWorld.d.ts.map +1 -1
  340. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DOMWorld.js +662 -654
  341. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DOMWorld.js.map +1 -1
  342. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Debug.d.ts +52 -52
  343. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Debug.js +81 -81
  344. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DeviceDescriptors.d.ts +40 -40
  345. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DeviceDescriptors.d.ts.map +1 -1
  346. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DeviceDescriptors.js +1070 -950
  347. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DeviceDescriptors.js.map +1 -1
  348. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Dialog.d.ts +74 -74
  349. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Dialog.js +97 -97
  350. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Dialog.js.map +1 -1
  351. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EmulationManager.d.ts +24 -24
  352. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EmulationManager.js +37 -37
  353. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Errors.d.ts +50 -41
  354. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Errors.d.ts.map +1 -1
  355. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Errors.js +56 -48
  356. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Errors.js.map +1 -1
  357. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EvalTypes.d.ts +60 -60
  358. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EvalTypes.d.ts.map +1 -1
  359. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EvalTypes.js +17 -17
  360. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.d.ts +92 -92
  361. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js +116 -116
  362. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js.map +1 -1
  363. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Events.d.ts +81 -81
  364. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Events.js +86 -86
  365. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ExecutionContext.d.ts +193 -193
  366. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ExecutionContext.js +321 -321
  367. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ExecutionContext.js.map +1 -1
  368. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FileChooser.d.ts +58 -58
  369. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FileChooser.js +71 -71
  370. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FileChooser.js.map +1 -1
  371. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FrameManager.d.ts +744 -732
  372. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FrameManager.d.ts.map +1 -1
  373. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FrameManager.js +1047 -964
  374. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FrameManager.js.map +1 -1
  375. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest.d.ts +350 -340
  376. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest.d.ts.map +1 -1
  377. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest.js +549 -546
  378. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest.js.map +1 -1
  379. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPResponse.d.ts +134 -125
  380. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPResponse.d.ts.map +1 -1
  381. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPResponse.js +184 -154
  382. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPResponse.js.map +1 -1
  383. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Input.d.ts +358 -359
  384. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Input.d.ts.map +1 -1
  385. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Input.js +543 -544
  386. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Input.js.map +1 -1
  387. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/JSHandle.d.ts +490 -468
  388. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/JSHandle.d.ts.map +1 -1
  389. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/JSHandle.js +827 -802
  390. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/JSHandle.js.map +1 -1
  391. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.d.ts +65 -65
  392. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.d.ts.map +1 -1
  393. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.js +149 -148
  394. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.js.map +1 -1
  395. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkConditions.d.ts +26 -26
  396. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkConditions.js +33 -33
  397. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManager.d.ts +126 -96
  398. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManager.d.ts.map +1 -1
  399. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManager.js +467 -340
  400. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManager.js.map +1 -1
  401. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.d.ts +161 -156
  402. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.d.ts.map +1 -1
  403. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.js +34 -34
  404. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.js.map +1 -1
  405. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.d.ts +2055 -2010
  406. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.d.ts.map +1 -1
  407. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.js +2533 -2426
  408. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.js.map +1 -1
  409. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Product.d.ts +20 -20
  410. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Product.js +17 -17
  411. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Puppeteer.d.ts +159 -159
  412. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Puppeteer.js +161 -161
  413. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Puppeteer.js.map +1 -1
  414. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PuppeteerViewport.d.ts +51 -51
  415. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PuppeteerViewport.js +2 -2
  416. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/QueryHandler.d.ts +64 -64
  417. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/QueryHandler.js +165 -165
  418. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/SecurityDetails.d.ts +60 -60
  419. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/SecurityDetails.js +76 -76
  420. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Target.d.ts +100 -98
  421. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Target.d.ts.map +1 -1
  422. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Target.js +145 -144
  423. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Target.js.map +1 -1
  424. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.d.ts +21 -0
  425. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.d.ts.map +1 -0
  426. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.js +30 -0
  427. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.js.map +1 -0
  428. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TimeoutSettings.d.ts +27 -27
  429. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TimeoutSettings.js +47 -47
  430. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Tracing.d.ts +46 -46
  431. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Tracing.d.ts.map +1 -1
  432. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Tracing.js +109 -103
  433. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Tracing.js.map +1 -1
  434. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.d.ts +39 -39
  435. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.js +406 -406
  436. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WebWorker.d.ts +98 -98
  437. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WebWorker.js +112 -112
  438. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/assert.d.ts +22 -21
  439. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/assert.d.ts.map +1 -1
  440. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/assert.js +33 -28
  441. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/assert.js.map +1 -1
  442. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/fetch.d.ts +16 -16
  443. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/fetch.js +43 -43
  444. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/helper.d.ts +84 -84
  445. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/helper.js +327 -327
  446. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/helper.js.map +1 -1
  447. data/node_modules/puppeteer-core/lib/cjs/puppeteer/environment.d.ts +16 -16
  448. data/node_modules/puppeteer-core/lib/cjs/puppeteer/environment.js +19 -19
  449. data/node_modules/puppeteer-core/lib/cjs/puppeteer/global.d.ts +17 -0
  450. data/node_modules/puppeteer-core/lib/cjs/puppeteer/global.d.ts.map +1 -0
  451. data/node_modules/puppeteer-core/lib/cjs/puppeteer/global.js +3 -0
  452. data/node_modules/puppeteer-core/lib/cjs/puppeteer/global.js.map +1 -0
  453. data/node_modules/puppeteer-core/lib/cjs/puppeteer/initialize-node.d.ts +17 -17
  454. data/node_modules/puppeteer-core/lib/cjs/puppeteer/initialize-node.js +44 -44
  455. data/node_modules/puppeteer-core/lib/cjs/puppeteer/initialize-web.d.ts +17 -17
  456. data/node_modules/puppeteer-core/lib/cjs/puppeteer/initialize-web.js +26 -26
  457. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserFetcher.d.ts +133 -133
  458. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserFetcher.d.ts.map +1 -1
  459. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserFetcher.js +500 -501
  460. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserFetcher.js.map +1 -1
  461. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.d.ts +40 -39
  462. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.d.ts.map +1 -1
  463. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.js +256 -224
  464. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.js.map +1 -1
  465. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/LaunchOptions.d.ts +134 -130
  466. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/LaunchOptions.d.ts.map +1 -1
  467. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/LaunchOptions.js +17 -17
  468. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Launcher.d.ts +16 -16
  469. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Launcher.d.ts.map +1 -1
  470. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Launcher.js +655 -573
  471. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Launcher.js.map +1 -1
  472. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.d.ts +26 -26
  473. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.d.ts.map +1 -1
  474. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.js +47 -41
  475. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.js.map +1 -1
  476. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/PipeTransport.d.ts +29 -29
  477. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/PipeTransport.js +64 -64
  478. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Puppeteer.d.ts +153 -153
  479. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Puppeteer.js +188 -188
  480. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Puppeteer.js.map +1 -1
  481. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/install.d.ts +17 -17
  482. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/install.d.ts.map +1 -1
  483. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/install.js +173 -159
  484. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/install.js.map +1 -1
  485. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node-puppeteer-core.d.ts +17 -17
  486. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node-puppeteer-core.js +24 -24
  487. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node-puppeteer-core.js.map +1 -1
  488. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node.d.ts +17 -17
  489. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node.js +23 -23
  490. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node.js.map +1 -1
  491. data/node_modules/puppeteer-core/lib/cjs/puppeteer/revisions.d.ts +21 -21
  492. data/node_modules/puppeteer-core/lib/cjs/puppeteer/revisions.js +22 -22
  493. data/node_modules/puppeteer-core/lib/cjs/puppeteer/web.d.ts +17 -17
  494. data/node_modules/puppeteer-core/lib/cjs/puppeteer/web.js +23 -23
  495. data/node_modules/puppeteer-core/lib/cjs/puppeteer/web.js.map +1 -1
  496. data/node_modules/puppeteer-core/lib/cjs/vendor/mitt/src/index.d.ts +27 -27
  497. data/node_modules/puppeteer-core/lib/cjs/vendor/mitt/src/index.js +56 -56
  498. data/node_modules/puppeteer-core/lib/esm/puppeteer/api-docs-entry.d.ts +110 -110
  499. data/node_modules/puppeteer-core/lib/esm/puppeteer/api-docs-entry.js +80 -80
  500. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Accessibility.d.ts +175 -175
  501. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Accessibility.js +356 -356
  502. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/AriaQueryHandler.d.ts +20 -20
  503. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/AriaQueryHandler.d.ts.map +1 -1
  504. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/AriaQueryHandler.js +81 -81
  505. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/AriaQueryHandler.js.map +1 -1
  506. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Browser.d.ts +455 -437
  507. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Browser.d.ts.map +1 -1
  508. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Browser.js +535 -522
  509. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Browser.js.map +1 -1
  510. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/BrowserConnector.d.ts +53 -53
  511. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/BrowserConnector.js +74 -74
  512. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/BrowserWebSocketTransport.d.ts +25 -25
  513. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/BrowserWebSocketTransport.js +30 -30
  514. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Connection.d.ts +135 -129
  515. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Connection.d.ts.map +1 -1
  516. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Connection.js +293 -275
  517. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Connection.js.map +1 -1
  518. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ConnectionTransport.d.ts +24 -24
  519. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ConnectionTransport.js +16 -16
  520. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ConsoleMessage.d.ts +72 -72
  521. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ConsoleMessage.js +60 -60
  522. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Coverage.d.ts +204 -188
  523. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Coverage.d.ts.map +1 -1
  524. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Coverage.js +329 -322
  525. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Coverage.js.map +1 -1
  526. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DOMWorld.d.ts +175 -172
  527. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DOMWorld.d.ts.map +1 -1
  528. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DOMWorld.js +657 -649
  529. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DOMWorld.js.map +1 -1
  530. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Debug.d.ts +52 -52
  531. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Debug.js +77 -77
  532. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DeviceDescriptors.d.ts +40 -40
  533. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DeviceDescriptors.d.ts.map +1 -1
  534. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DeviceDescriptors.js +1067 -947
  535. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DeviceDescriptors.js.map +1 -1
  536. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Dialog.d.ts +74 -74
  537. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Dialog.js +93 -93
  538. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EmulationManager.d.ts +24 -24
  539. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EmulationManager.js +33 -33
  540. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Errors.d.ts +50 -41
  541. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Errors.d.ts.map +1 -1
  542. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Errors.js +50 -43
  543. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Errors.js.map +1 -1
  544. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EvalTypes.d.ts +60 -60
  545. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EvalTypes.d.ts.map +1 -1
  546. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EvalTypes.js +16 -16
  547. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EventEmitter.d.ts +92 -92
  548. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EventEmitter.js +109 -109
  549. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Events.d.ts +81 -81
  550. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Events.js +83 -83
  551. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ExecutionContext.d.ts +193 -193
  552. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ExecutionContext.js +317 -317
  553. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FileChooser.d.ts +58 -58
  554. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FileChooser.js +67 -67
  555. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FrameManager.d.ts +744 -732
  556. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FrameManager.d.ts.map +1 -1
  557. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FrameManager.js +1042 -959
  558. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FrameManager.js.map +1 -1
  559. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPRequest.d.ts +350 -340
  560. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPRequest.d.ts.map +1 -1
  561. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPRequest.js +545 -542
  562. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPRequest.js.map +1 -1
  563. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPResponse.d.ts +134 -125
  564. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPResponse.d.ts.map +1 -1
  565. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPResponse.js +180 -150
  566. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPResponse.js.map +1 -1
  567. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Input.d.ts +358 -359
  568. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Input.d.ts.map +1 -1
  569. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Input.js +537 -538
  570. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Input.js.map +1 -1
  571. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/JSHandle.d.ts +490 -468
  572. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/JSHandle.d.ts.map +1 -1
  573. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/JSHandle.js +802 -777
  574. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/JSHandle.js.map +1 -1
  575. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/LifecycleWatcher.d.ts +65 -65
  576. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/LifecycleWatcher.d.ts.map +1 -1
  577. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/LifecycleWatcher.js +145 -144
  578. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/LifecycleWatcher.js.map +1 -1
  579. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkConditions.d.ts +26 -26
  580. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkConditions.js +30 -30
  581. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkManager.d.ts +126 -96
  582. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkManager.d.ts.map +1 -1
  583. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkManager.js +463 -336
  584. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkManager.js.map +1 -1
  585. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PDFOptions.d.ts +161 -156
  586. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PDFOptions.d.ts.map +1 -1
  587. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PDFOptions.js +31 -31
  588. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PDFOptions.js.map +1 -1
  589. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Page.d.ts +2055 -2010
  590. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Page.d.ts.map +1 -1
  591. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Page.js +2529 -2422
  592. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Page.js.map +1 -1
  593. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Product.d.ts +20 -20
  594. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Product.js +16 -16
  595. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Puppeteer.d.ts +159 -159
  596. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Puppeteer.js +157 -157
  597. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PuppeteerViewport.d.ts +51 -51
  598. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PuppeteerViewport.js +1 -1
  599. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/QueryHandler.d.ts +64 -64
  600. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/QueryHandler.js +157 -157
  601. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/SecurityDetails.d.ts +60 -60
  602. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/SecurityDetails.js +72 -72
  603. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Target.d.ts +100 -98
  604. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Target.d.ts.map +1 -1
  605. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Target.js +141 -140
  606. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Target.js.map +1 -1
  607. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TaskQueue.d.ts +21 -0
  608. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TaskQueue.d.ts.map +1 -0
  609. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TaskQueue.js +26 -0
  610. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TaskQueue.js.map +1 -0
  611. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TimeoutSettings.d.ts +27 -27
  612. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TimeoutSettings.js +43 -43
  613. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Tracing.d.ts +46 -46
  614. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Tracing.d.ts.map +1 -1
  615. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Tracing.js +105 -99
  616. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Tracing.js.map +1 -1
  617. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/USKeyboardLayout.d.ts +39 -39
  618. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/USKeyboardLayout.js +403 -403
  619. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/WebWorker.d.ts +98 -98
  620. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/WebWorker.js +108 -108
  621. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/assert.d.ts +22 -21
  622. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/assert.d.ts.map +1 -1
  623. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/assert.js +28 -24
  624. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/assert.js.map +1 -1
  625. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/fetch.d.ts +16 -16
  626. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/fetch.js +20 -20
  627. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/helper.d.ts +84 -84
  628. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/helper.js +305 -305
  629. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/helper.js.map +1 -1
  630. data/node_modules/puppeteer-core/lib/esm/puppeteer/environment.d.ts +16 -16
  631. data/node_modules/puppeteer-core/lib/esm/puppeteer/environment.js +16 -16
  632. data/node_modules/puppeteer-core/lib/esm/puppeteer/global.d.ts +17 -0
  633. data/node_modules/puppeteer-core/lib/esm/puppeteer/global.d.ts.map +1 -0
  634. data/node_modules/puppeteer-core/lib/esm/puppeteer/global.js +2 -0
  635. data/node_modules/puppeteer-core/lib/esm/puppeteer/global.js.map +1 -0
  636. data/node_modules/puppeteer-core/lib/esm/puppeteer/initialize-node.d.ts +17 -17
  637. data/node_modules/puppeteer-core/lib/esm/puppeteer/initialize-node.js +37 -37
  638. data/node_modules/puppeteer-core/lib/esm/puppeteer/initialize-web.d.ts +17 -17
  639. data/node_modules/puppeteer-core/lib/esm/puppeteer/initialize-web.js +22 -22
  640. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserFetcher.d.ts +133 -133
  641. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserFetcher.d.ts.map +1 -1
  642. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserFetcher.js +474 -475
  643. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserFetcher.js.map +1 -1
  644. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.d.ts +40 -39
  645. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.d.ts.map +1 -1
  646. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js +230 -198
  647. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js.map +1 -1
  648. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/LaunchOptions.d.ts +134 -130
  649. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/LaunchOptions.d.ts.map +1 -1
  650. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/LaunchOptions.js +16 -16
  651. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Launcher.d.ts +16 -16
  652. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Launcher.d.ts.map +1 -1
  653. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Launcher.js +633 -551
  654. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Launcher.js.map +1 -1
  655. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/NodeWebSocketTransport.d.ts +26 -26
  656. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/NodeWebSocketTransport.d.ts.map +1 -1
  657. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/NodeWebSocketTransport.js +40 -34
  658. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/NodeWebSocketTransport.js.map +1 -1
  659. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/PipeTransport.d.ts +29 -29
  660. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/PipeTransport.js +60 -60
  661. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Puppeteer.d.ts +153 -153
  662. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Puppeteer.js +181 -181
  663. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/install.d.ts +17 -17
  664. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/install.d.ts.map +1 -1
  665. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/install.js +165 -151
  666. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/install.js.map +1 -1
  667. data/node_modules/puppeteer-core/lib/esm/puppeteer/node-puppeteer-core.d.ts +17 -17
  668. data/node_modules/puppeteer-core/lib/esm/puppeteer/node-puppeteer-core.js +22 -22
  669. data/node_modules/puppeteer-core/lib/esm/puppeteer/node.d.ts +17 -17
  670. data/node_modules/puppeteer-core/lib/esm/puppeteer/node.js +21 -21
  671. data/node_modules/puppeteer-core/lib/esm/puppeteer/revisions.d.ts +21 -21
  672. data/node_modules/puppeteer-core/lib/esm/puppeteer/revisions.js +19 -19
  673. data/node_modules/puppeteer-core/lib/esm/puppeteer/web.d.ts +17 -17
  674. data/node_modules/puppeteer-core/lib/esm/puppeteer/web.js +21 -21
  675. data/node_modules/puppeteer-core/lib/esm/vendor/mitt/src/index.d.ts +27 -27
  676. data/node_modules/puppeteer-core/lib/esm/vendor/mitt/src/index.js +53 -53
  677. data/node_modules/puppeteer-core/lib/types.d.ts +3965 -3735
  678. data/node_modules/puppeteer-core/package.json +115 -121
  679. data/node_modules/puppeteer-core/typescript-if-required.js +61 -61
  680. data/node_modules/readable-stream/CONTRIBUTING.md +38 -38
  681. data/node_modules/readable-stream/GOVERNANCE.md +136 -136
  682. data/node_modules/readable-stream/LICENSE +47 -47
  683. data/node_modules/readable-stream/README.md +106 -106
  684. data/node_modules/readable-stream/errors-browser.js +127 -127
  685. data/node_modules/readable-stream/errors.js +116 -116
  686. data/node_modules/readable-stream/experimentalWarning.js +17 -17
  687. data/node_modules/readable-stream/lib/_stream_duplex.js +138 -138
  688. data/node_modules/readable-stream/lib/_stream_passthrough.js +38 -38
  689. data/node_modules/readable-stream/lib/_stream_readable.js +1123 -1123
  690. data/node_modules/readable-stream/lib/_stream_transform.js +200 -200
  691. data/node_modules/readable-stream/lib/_stream_writable.js +696 -696
  692. data/node_modules/readable-stream/lib/internal/streams/async_iterator.js +206 -206
  693. data/node_modules/readable-stream/lib/internal/streams/buffer_list.js +209 -209
  694. data/node_modules/readable-stream/lib/internal/streams/destroy.js +104 -104
  695. data/node_modules/readable-stream/lib/internal/streams/end-of-stream.js +103 -103
  696. data/node_modules/readable-stream/lib/internal/streams/from-browser.js +3 -3
  697. data/node_modules/readable-stream/lib/internal/streams/from.js +63 -63
  698. data/node_modules/readable-stream/lib/internal/streams/pipeline.js +96 -96
  699. data/node_modules/readable-stream/lib/internal/streams/state.js +26 -26
  700. data/node_modules/readable-stream/lib/internal/streams/stream-browser.js +1 -1
  701. data/node_modules/readable-stream/lib/internal/streams/stream.js +1 -1
  702. data/node_modules/readable-stream/package.json +68 -68
  703. data/node_modules/readable-stream/readable-browser.js +9 -9
  704. data/node_modules/readable-stream/readable.js +16 -16
  705. data/node_modules/rimraf/CHANGELOG.md +65 -65
  706. data/node_modules/rimraf/LICENSE +15 -15
  707. data/node_modules/rimraf/README.md +101 -101
  708. data/node_modules/rimraf/bin.js +68 -68
  709. data/node_modules/rimraf/package.json +32 -32
  710. data/node_modules/rimraf/rimraf.js +360 -360
  711. data/node_modules/safe-buffer/LICENSE +21 -21
  712. data/node_modules/safe-buffer/README.md +584 -584
  713. data/node_modules/safe-buffer/index.d.ts +186 -186
  714. data/node_modules/safe-buffer/index.js +65 -65
  715. data/node_modules/safe-buffer/package.json +51 -51
  716. data/node_modules/string_decoder/LICENSE +48 -48
  717. data/node_modules/string_decoder/README.md +47 -47
  718. data/node_modules/string_decoder/lib/string_decoder.js +295 -295
  719. data/node_modules/string_decoder/package.json +34 -34
  720. data/node_modules/tar-fs/.travis.yml +6 -5
  721. data/node_modules/tar-fs/LICENSE +20 -20
  722. data/node_modules/tar-fs/README.md +165 -163
  723. data/node_modules/tar-fs/index.js +351 -348
  724. data/node_modules/tar-fs/package.json +41 -41
  725. data/node_modules/tar-fs/test/fixtures/a/hello.txt +1 -1
  726. data/node_modules/tar-fs/test/fixtures/b/a/test.txt +1 -1
  727. data/node_modules/tar-fs/test/index.js +346 -346
  728. data/node_modules/tar-stream/LICENSE +20 -20
  729. data/node_modules/tar-stream/README.md +168 -168
  730. data/node_modules/tar-stream/extract.js +257 -257
  731. data/node_modules/tar-stream/headers.js +295 -295
  732. data/node_modules/tar-stream/index.js +2 -2
  733. data/node_modules/tar-stream/pack.js +255 -255
  734. data/node_modules/tar-stream/package.json +58 -58
  735. data/node_modules/tar-stream/sandbox.js +11 -11
  736. data/node_modules/through/.travis.yml +5 -5
  737. data/node_modules/through/LICENSE.APACHE2 +15 -15
  738. data/node_modules/through/LICENSE.MIT +24 -24
  739. data/node_modules/through/index.js +108 -108
  740. data/node_modules/through/package.json +36 -36
  741. data/node_modules/through/readme.markdown +64 -64
  742. data/node_modules/through/test/async.js +28 -28
  743. data/node_modules/through/test/auto-destroy.js +30 -30
  744. data/node_modules/through/test/buffering.js +71 -71
  745. data/node_modules/through/test/end.js +45 -45
  746. data/node_modules/through/test/index.js +133 -133
  747. data/node_modules/tr46/.npmignore +4 -0
  748. data/node_modules/tr46/index.js +193 -0
  749. data/node_modules/tr46/lib/.gitkeep +0 -0
  750. data/node_modules/tr46/lib/mappingTable.json +1 -0
  751. data/node_modules/tr46/package.json +31 -0
  752. data/node_modules/unbzip2-stream/LICENSE +24 -24
  753. data/node_modules/unbzip2-stream/README.md +59 -59
  754. data/node_modules/unbzip2-stream/dist/unbzip2-stream.min.js +1 -1
  755. data/node_modules/unbzip2-stream/index.js +93 -92
  756. data/node_modules/unbzip2-stream/lib/bit_iterator.js +39 -39
  757. data/node_modules/unbzip2-stream/lib/bzip2.js +365 -367
  758. data/node_modules/unbzip2-stream/package.json +51 -51
  759. data/node_modules/util-deprecate/History.md +16 -16
  760. data/node_modules/util-deprecate/LICENSE +24 -24
  761. data/node_modules/util-deprecate/README.md +53 -53
  762. data/node_modules/util-deprecate/browser.js +67 -67
  763. data/node_modules/util-deprecate/node.js +6 -6
  764. data/node_modules/util-deprecate/package.json +27 -27
  765. data/node_modules/webidl-conversions/LICENSE.md +12 -0
  766. data/node_modules/webidl-conversions/README.md +53 -0
  767. data/node_modules/webidl-conversions/lib/index.js +189 -0
  768. data/node_modules/webidl-conversions/package.json +23 -0
  769. data/node_modules/whatwg-url/LICENSE.txt +21 -0
  770. data/node_modules/whatwg-url/README.md +67 -0
  771. data/node_modules/whatwg-url/lib/URL-impl.js +200 -0
  772. data/node_modules/whatwg-url/lib/URL.js +196 -0
  773. data/node_modules/whatwg-url/lib/public-api.js +11 -0
  774. data/node_modules/whatwg-url/lib/url-state-machine.js +1297 -0
  775. data/node_modules/whatwg-url/lib/utils.js +20 -0
  776. data/node_modules/whatwg-url/package.json +32 -0
  777. data/node_modules/wrappy/LICENSE +15 -15
  778. data/node_modules/wrappy/README.md +36 -36
  779. data/node_modules/wrappy/package.json +29 -29
  780. data/node_modules/wrappy/wrappy.js +33 -33
  781. data/node_modules/ws/LICENSE +19 -21
  782. data/node_modules/ws/README.md +493 -496
  783. data/node_modules/ws/browser.js +8 -8
  784. data/node_modules/ws/index.js +13 -10
  785. data/node_modules/ws/lib/buffer-util.js +126 -129
  786. data/node_modules/ws/lib/constants.js +12 -10
  787. data/node_modules/ws/lib/event-target.js +266 -184
  788. data/node_modules/ws/lib/extension.js +203 -223
  789. data/node_modules/ws/lib/limiter.js +55 -55
  790. data/node_modules/ws/lib/permessage-deflate.js +511 -517
  791. data/node_modules/ws/lib/receiver.js +612 -507
  792. data/node_modules/ws/lib/sender.js +422 -405
  793. data/node_modules/ws/lib/stream.js +180 -165
  794. data/node_modules/ws/lib/subprotocol.js +62 -0
  795. data/node_modules/ws/lib/validation.js +124 -104
  796. data/node_modules/ws/lib/websocket-server.js +485 -418
  797. data/node_modules/ws/lib/websocket.js +1149 -942
  798. data/node_modules/ws/package.json +61 -56
  799. data/node_modules/ws/wrapper.mjs +8 -0
  800. data/node_modules/yauzl/LICENSE +21 -21
  801. data/node_modules/yauzl/README.md +658 -658
  802. data/node_modules/yauzl/index.js +796 -796
  803. data/node_modules/yauzl/package.json +40 -40
  804. data/package.json +1 -1
  805. metadata +81 -61
  806. data/node_modules/.bin/mkdirp +0 -12
  807. data/node_modules/.bin/mkdirp.cmd +0 -17
  808. data/node_modules/.bin/mkdirp.ps1 +0 -28
  809. data/node_modules/devtools-protocol/changelog.md +0 -10491
  810. data/node_modules/devtools-protocol/externs/protocol_externs.js +0 -9734
  811. data/node_modules/minimist/.travis.yml +0 -8
  812. data/node_modules/minimist/LICENSE +0 -18
  813. data/node_modules/minimist/example/parse.js +0 -2
  814. data/node_modules/minimist/index.js +0 -245
  815. data/node_modules/minimist/package.json +0 -45
  816. data/node_modules/minimist/readme.markdown +0 -95
  817. data/node_modules/minimist/test/all_bool.js +0 -32
  818. data/node_modules/minimist/test/bool.js +0 -178
  819. data/node_modules/minimist/test/dash.js +0 -31
  820. data/node_modules/minimist/test/default_bool.js +0 -35
  821. data/node_modules/minimist/test/dotted.js +0 -22
  822. data/node_modules/minimist/test/kv_short.js +0 -16
  823. data/node_modules/minimist/test/long.js +0 -31
  824. data/node_modules/minimist/test/num.js +0 -36
  825. data/node_modules/minimist/test/parse.js +0 -197
  826. data/node_modules/minimist/test/parse_modified.js +0 -9
  827. data/node_modules/minimist/test/proto.js +0 -44
  828. data/node_modules/minimist/test/short.js +0 -67
  829. data/node_modules/minimist/test/stop_early.js +0 -15
  830. data/node_modules/minimist/test/unknown.js +0 -102
  831. data/node_modules/minimist/test/whitespace.js +0 -8
  832. data/node_modules/mkdirp/bin/cmd.js +0 -33
  833. data/node_modules/mkdirp/bin/usage.txt +0 -12
  834. data/node_modules/mkdirp/package.json +0 -34
  835. data/node_modules/mkdirp/readme.markdown +0 -100
  836. data/node_modules/node-fetch/CHANGELOG.md +0 -272
@@ -1,2423 +1,2530 @@
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
- */
16
- import { EventEmitter } from './EventEmitter.js';
17
- import { Connection, CDPSessionEmittedEvents, } from './Connection.js';
18
- import { Dialog } from './Dialog.js';
19
- import { EmulationManager } from './EmulationManager.js';
20
- import { FrameManager, FrameManagerEmittedEvents, } from './FrameManager.js';
21
- import { Keyboard, Mouse, Touchscreen } from './Input.js';
22
- import { Tracing } from './Tracing.js';
23
- import { assert } from './assert.js';
24
- import { helper, debugError } from './helper.js';
25
- import { Coverage } from './Coverage.js';
26
- import { WebWorker } from './WebWorker.js';
27
- import { createJSHandle } from './JSHandle.js';
28
- import { NetworkManagerEmittedEvents, } from './NetworkManager.js';
29
- import { Accessibility } from './Accessibility.js';
30
- import { TimeoutSettings } from './TimeoutSettings.js';
31
- import { FileChooser } from './FileChooser.js';
32
- import { ConsoleMessage } from './ConsoleMessage.js';
33
- import { paperFormats } from './PDFOptions.js';
34
- import { isNode } from '../environment.js';
35
- class ScreenshotTaskQueue {
36
- constructor() {
37
- this._chain = Promise.resolve(undefined);
38
- }
39
- postTask(task) {
40
- const result = this._chain.then(task);
41
- this._chain = result.catch(() => { });
42
- return result;
43
- }
44
- }
45
- /**
46
- * Page provides methods to interact with a single tab or
47
- * {@link https://developer.chrome.com/extensions/background_pages | extension background page} in Chromium.
48
- *
49
- * @remarks
50
- *
51
- * One Browser instance might have multiple Page instances.
52
- *
53
- * @example
54
- * This example creates a page, navigates it to a URL, and then * saves a screenshot:
55
- * ```js
56
- * const puppeteer = require('puppeteer');
57
- *
58
- * (async () => {
59
- * const browser = await puppeteer.launch();
60
- * const page = await browser.newPage();
61
- * await page.goto('https://example.com');
62
- * await page.screenshot({path: 'screenshot.png'});
63
- * await browser.close();
64
- * })();
65
- * ```
66
- *
67
- * The Page class extends from Puppeteer's {@link EventEmitter} class and will
68
- * emit various events which are documented in the {@link PageEmittedEvents} enum.
69
- *
70
- * @example
71
- * This example logs a message for a single page `load` event:
72
- * ```js
73
- * page.once('load', () => console.log('Page loaded!'));
74
- * ```
75
- *
76
- * To unsubscribe from events use the `off` method:
77
- *
78
- * ```js
79
- * function logRequest(interceptedRequest) {
80
- * console.log('A request was made:', interceptedRequest.url());
81
- * }
82
- * page.on('request', logRequest);
83
- * // Sometime later...
84
- * page.off('request', logRequest);
85
- * ```
86
- * @public
87
- */
88
- export class Page extends EventEmitter {
89
- /**
90
- * @internal
91
- */
92
- constructor(client, target, ignoreHTTPSErrors) {
93
- super();
94
- this._closed = false;
95
- this._timeoutSettings = new TimeoutSettings();
96
- this._pageBindings = new Map();
97
- this._javascriptEnabled = true;
98
- this._workers = new Map();
99
- // TODO: improve this typedef - it's a function that takes a file chooser or
100
- // something?
101
- this._fileChooserInterceptors = new Set();
102
- this._userDragInterceptionEnabled = false;
103
- this._client = client;
104
- this._target = target;
105
- this._keyboard = new Keyboard(client);
106
- this._mouse = new Mouse(client, this._keyboard);
107
- this._touchscreen = new Touchscreen(client, this._keyboard);
108
- this._accessibility = new Accessibility(client);
109
- this._frameManager = new FrameManager(client, this, ignoreHTTPSErrors, this._timeoutSettings);
110
- this._emulationManager = new EmulationManager(client);
111
- this._tracing = new Tracing(client);
112
- this._coverage = new Coverage(client);
113
- this._screenshotTaskQueue = new ScreenshotTaskQueue();
114
- this._viewport = null;
115
- client.on('Target.attachedToTarget', (event) => {
116
- if (event.targetInfo.type !== 'worker' &&
117
- event.targetInfo.type !== 'iframe') {
118
- // If we don't detach from service workers, they will never die.
119
- // We still want to attach to workers for emitting events.
120
- // We still want to attach to iframes so sessions may interact with them.
121
- // We detach from all other types out of an abundance of caution.
122
- // See https://source.chromium.org/chromium/chromium/src/+/master:content/browser/devtools/devtools_agent_host_impl.cc?q=f:devtools%20-f:out%20%22::kTypePage%5B%5D%22&ss=chromium
123
- // for the complete list of available types.
124
- client
125
- .send('Target.detachFromTarget', {
126
- sessionId: event.sessionId,
127
- })
128
- .catch(debugError);
129
- return;
130
- }
131
- const session = Connection.fromSession(client).session(event.sessionId);
132
- const worker = new WebWorker(session, event.targetInfo.url, this._addConsoleMessage.bind(this), this._handleException.bind(this));
133
- this._workers.set(event.sessionId, worker);
134
- this.emit("workercreated" /* WorkerCreated */, worker);
135
- });
136
- client.on('Target.detachedFromTarget', (event) => {
137
- const worker = this._workers.get(event.sessionId);
138
- if (!worker)
139
- return;
140
- this._workers.delete(event.sessionId);
141
- this.emit("workerdestroyed" /* WorkerDestroyed */, worker);
142
- });
143
- this._frameManager.on(FrameManagerEmittedEvents.FrameAttached, (event) => this.emit("frameattached" /* FrameAttached */, event));
144
- this._frameManager.on(FrameManagerEmittedEvents.FrameDetached, (event) => this.emit("framedetached" /* FrameDetached */, event));
145
- this._frameManager.on(FrameManagerEmittedEvents.FrameNavigated, (event) => this.emit("framenavigated" /* FrameNavigated */, event));
146
- const networkManager = this._frameManager.networkManager();
147
- networkManager.on(NetworkManagerEmittedEvents.Request, (event) => this.emit("request" /* Request */, event));
148
- networkManager.on(NetworkManagerEmittedEvents.RequestServedFromCache, (event) => this.emit("requestservedfromcache" /* RequestServedFromCache */, event));
149
- networkManager.on(NetworkManagerEmittedEvents.Response, (event) => this.emit("response" /* Response */, event));
150
- networkManager.on(NetworkManagerEmittedEvents.RequestFailed, (event) => this.emit("requestfailed" /* RequestFailed */, event));
151
- networkManager.on(NetworkManagerEmittedEvents.RequestFinished, (event) => this.emit("requestfinished" /* RequestFinished */, event));
152
- this._fileChooserInterceptors = new Set();
153
- client.on('Page.domContentEventFired', () => this.emit("domcontentloaded" /* DOMContentLoaded */));
154
- client.on('Page.loadEventFired', () => this.emit("load" /* Load */));
155
- client.on('Runtime.consoleAPICalled', (event) => this._onConsoleAPI(event));
156
- client.on('Runtime.bindingCalled', (event) => this._onBindingCalled(event));
157
- client.on('Page.javascriptDialogOpening', (event) => this._onDialog(event));
158
- client.on('Runtime.exceptionThrown', (exception) => this._handleException(exception.exceptionDetails));
159
- client.on('Inspector.targetCrashed', () => this._onTargetCrashed());
160
- client.on('Performance.metrics', (event) => this._emitMetrics(event));
161
- client.on('Log.entryAdded', (event) => this._onLogEntryAdded(event));
162
- client.on('Page.fileChooserOpened', (event) => this._onFileChooser(event));
163
- this._target._isClosedPromise.then(() => {
164
- this.emit("close" /* Close */);
165
- this._closed = true;
166
- });
167
- }
168
- /**
169
- * @internal
170
- */
171
- static async create(client, target, ignoreHTTPSErrors, defaultViewport) {
172
- const page = new Page(client, target, ignoreHTTPSErrors);
173
- await page._initialize();
174
- if (defaultViewport)
175
- await page.setViewport(defaultViewport);
176
- return page;
177
- }
178
- async _initialize() {
179
- await Promise.all([
180
- this._frameManager.initialize(),
181
- this._client.send('Target.setAutoAttach', {
182
- autoAttach: true,
183
- waitForDebuggerOnStart: false,
184
- flatten: true,
185
- }),
186
- this._client.send('Performance.enable'),
187
- this._client.send('Log.enable'),
188
- ]);
189
- }
190
- async _onFileChooser(event) {
191
- if (!this._fileChooserInterceptors.size)
192
- return;
193
- const frame = this._frameManager.frame(event.frameId);
194
- const context = await frame.executionContext();
195
- const element = await context._adoptBackendNodeId(event.backendNodeId);
196
- const interceptors = Array.from(this._fileChooserInterceptors);
197
- this._fileChooserInterceptors.clear();
198
- const fileChooser = new FileChooser(element, event);
199
- for (const interceptor of interceptors)
200
- interceptor.call(null, fileChooser);
201
- }
202
- /**
203
- * @returns `true` if drag events are being intercepted, `false` otherwise.
204
- */
205
- isDragInterceptionEnabled() {
206
- return this._userDragInterceptionEnabled;
207
- }
208
- /**
209
- * @returns `true` if the page has JavaScript enabled, `false` otherwise.
210
- */
211
- isJavaScriptEnabled() {
212
- return this._javascriptEnabled;
213
- }
214
- /**
215
- * Listen to page events.
216
- */
217
- // Note: this method exists to define event typings and handle
218
- // proper wireup of cooperative request interception. Actual event listening and
219
- // dispatching is delegated to EventEmitter.
220
- on(eventName, handler) {
221
- if (eventName === 'request') {
222
- return super.on(eventName, (event) => {
223
- event.enqueueInterceptAction(() => handler(event));
224
- });
225
- }
226
- return super.on(eventName, handler);
227
- }
228
- once(eventName, handler) {
229
- // Note: this method only exists to define the types; we delegate the impl
230
- // to EventEmitter.
231
- return super.once(eventName, handler);
232
- }
233
- /**
234
- * This method is typically coupled with an action that triggers file
235
- * choosing. The following example clicks a button that issues a file chooser
236
- * and then responds with `/tmp/myfile.pdf` as if a user has selected this file.
237
- *
238
- * ```js
239
- * const [fileChooser] = await Promise.all([
240
- * page.waitForFileChooser(),
241
- * page.click('#upload-file-button'),
242
- * // some button that triggers file selection
243
- * ]);
244
- * await fileChooser.accept(['/tmp/myfile.pdf']);
245
- * ```
246
- *
247
- * NOTE: This must be called before the file chooser is launched. It will not
248
- * return a currently active file chooser.
249
- * @param options - Optional waiting parameters
250
- * @returns Resolves after a page requests a file picker.
251
- * @remarks
252
- * NOTE: In non-headless Chromium, this method results in the native file picker
253
- * dialog `not showing up` for the user.
254
- */
255
- async waitForFileChooser(options = {}) {
256
- if (!this._fileChooserInterceptors.size)
257
- await this._client.send('Page.setInterceptFileChooserDialog', {
258
- enabled: true,
259
- });
260
- const { timeout = this._timeoutSettings.timeout() } = options;
261
- let callback;
262
- const promise = new Promise((x) => (callback = x));
263
- this._fileChooserInterceptors.add(callback);
264
- return helper
265
- .waitWithTimeout(promise, 'waiting for file chooser', timeout)
266
- .catch((error) => {
267
- this._fileChooserInterceptors.delete(callback);
268
- throw error;
269
- });
270
- }
271
- /**
272
- * Sets the page's geolocation.
273
- * @remarks
274
- * NOTE: Consider using {@link BrowserContext.overridePermissions} to grant
275
- * permissions for the page to read its geolocation.
276
- * @example
277
- * ```js
278
- * await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
279
- * ```
280
- */
281
- async setGeolocation(options) {
282
- const { longitude, latitude, accuracy = 0 } = options;
283
- if (longitude < -180 || longitude > 180)
284
- throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
285
- if (latitude < -90 || latitude > 90)
286
- throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
287
- if (accuracy < 0)
288
- throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
289
- await this._client.send('Emulation.setGeolocationOverride', {
290
- longitude,
291
- latitude,
292
- accuracy,
293
- });
294
- }
295
- /**
296
- * @returns A target this page was created from.
297
- */
298
- target() {
299
- return this._target;
300
- }
301
- /**
302
- * Get the browser the page belongs to.
303
- */
304
- browser() {
305
- return this._target.browser();
306
- }
307
- /**
308
- * Get the browser context that the page belongs to.
309
- */
310
- browserContext() {
311
- return this._target.browserContext();
312
- }
313
- _onTargetCrashed() {
314
- this.emit('error', new Error('Page crashed!'));
315
- }
316
- _onLogEntryAdded(event) {
317
- const { level, text, args, source, url, lineNumber } = event.entry;
318
- if (args)
319
- args.map((arg) => helper.releaseObject(this._client, arg));
320
- if (source !== 'worker')
321
- this.emit("console" /* Console */, new ConsoleMessage(level, text, [], [{ url, lineNumber }]));
322
- }
323
- /**
324
- * @returns The page's main frame.
325
- * @remarks
326
- * Page is guaranteed to have a main frame which persists during navigations.
327
- */
328
- mainFrame() {
329
- return this._frameManager.mainFrame();
330
- }
331
- get keyboard() {
332
- return this._keyboard;
333
- }
334
- get touchscreen() {
335
- return this._touchscreen;
336
- }
337
- get coverage() {
338
- return this._coverage;
339
- }
340
- get tracing() {
341
- return this._tracing;
342
- }
343
- get accessibility() {
344
- return this._accessibility;
345
- }
346
- /**
347
- * @returns An array of all frames attached to the page.
348
- */
349
- frames() {
350
- return this._frameManager.frames();
351
- }
352
- /**
353
- * @returns all of the dedicated
354
- * {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API |
355
- * WebWorkers}
356
- * associated with the page.
357
- * @remarks
358
- * NOTE: This does not contain ServiceWorkers
359
- */
360
- workers() {
361
- return Array.from(this._workers.values());
362
- }
363
- /**
364
- * @param value - Whether to enable request interception.
365
- *
366
- * @remarks
367
- * Activating request interception enables {@link HTTPRequest.abort},
368
- * {@link HTTPRequest.continue} and {@link HTTPRequest.respond} methods. This
369
- * provides the capability to modify network requests that are made by a page.
370
- *
371
- * Once request interception is enabled, every request will stall unless it's
372
- * continued, responded or aborted; or completed using the browser cache.
373
- *
374
- * @example
375
- * An example of a naïve request interceptor that aborts all image requests:
376
- * ```js
377
- * const puppeteer = require('puppeteer');
378
- * (async () => {
379
- * const browser = await puppeteer.launch();
380
- * const page = await browser.newPage();
381
- * await page.setRequestInterception(true);
382
- * page.on('request', interceptedRequest => {
383
- * if (interceptedRequest.url().endsWith('.png') ||
384
- * interceptedRequest.url().endsWith('.jpg'))
385
- * interceptedRequest.abort();
386
- * else
387
- * interceptedRequest.continue();
388
- * });
389
- * await page.goto('https://example.com');
390
- * await browser.close();
391
- * })();
392
- * ```
393
- * NOTE: Enabling request interception disables page caching.
394
- */
395
- async setRequestInterception(value) {
396
- return this._frameManager.networkManager().setRequestInterception(value);
397
- }
398
- /**
399
- * @param enabled - Whether to enable drag interception.
400
- *
401
- * @remarks
402
- * Activating drag interception enables the `Input.drag`,
403
- * methods This provides the capability to capture drag events emitted
404
- * on the page, which can then be used to simulate drag-and-drop.
405
- */
406
- async setDragInterception(enabled) {
407
- this._userDragInterceptionEnabled = enabled;
408
- return this._client.send('Input.setInterceptDrags', { enabled });
409
- }
410
- /**
411
- * @param enabled - When `true`, enables offline mode for the page.
412
- * @remarks
413
- * NOTE: while this method sets the network connection to offline, it does
414
- * not change the parameters used in [page.emulateNetworkConditions(networkConditions)]
415
- * (#pageemulatenetworkconditionsnetworkconditions)
416
- */
417
- setOfflineMode(enabled) {
418
- return this._frameManager.networkManager().setOfflineMode(enabled);
419
- }
420
- /**
421
- * @param networkConditions - Passing `null` disables network condition emulation.
422
- * @example
423
- * ```js
424
- * const puppeteer = require('puppeteer');
425
- * const slow3G = puppeteer.networkConditions['Slow 3G'];
426
- *
427
- * (async () => {
428
- * const browser = await puppeteer.launch();
429
- * const page = await browser.newPage();
430
- * await page.emulateNetworkConditions(slow3G);
431
- * await page.goto('https://www.google.com');
432
- * // other actions...
433
- * await browser.close();
434
- * })();
435
- * ```
436
- * @remarks
437
- * NOTE: This does not affect WebSockets and WebRTC PeerConnections (see
438
- * https://crbug.com/563644). To set the page offline, you can use
439
- * [page.setOfflineMode(enabled)](#pagesetofflinemodeenabled).
440
- */
441
- emulateNetworkConditions(networkConditions) {
442
- return this._frameManager
443
- .networkManager()
444
- .emulateNetworkConditions(networkConditions);
445
- }
446
- /**
447
- * This setting will change the default maximum navigation time for the
448
- * following methods and related shortcuts:
449
- *
450
- * - {@link Page.goBack | page.goBack(options)}
451
- *
452
- * - {@link Page.goForward | page.goForward(options)}
453
- *
454
- * - {@link Page.goto | page.goto(url,options)}
455
- *
456
- * - {@link Page.reload | page.reload(options)}
457
- *
458
- * - {@link Page.setContent | page.setContent(html,options)}
459
- *
460
- * - {@link Page.waitForNavigation | page.waitForNavigation(options)}
461
- * @param timeout - Maximum navigation time in milliseconds.
462
- */
463
- setDefaultNavigationTimeout(timeout) {
464
- this._timeoutSettings.setDefaultNavigationTimeout(timeout);
465
- }
466
- /**
467
- * @param timeout - Maximum time in milliseconds.
468
- */
469
- setDefaultTimeout(timeout) {
470
- this._timeoutSettings.setDefaultTimeout(timeout);
471
- }
472
- /**
473
- * Runs `document.querySelector` within the page. If no element matches the
474
- * selector, the return value resolves to `null`.
475
- *
476
- * @remarks
477
- * Shortcut for {@link Frame.$ | Page.mainFrame().$(selector) }.
478
- *
479
- * @param selector - A `selector` to query page for
480
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
481
- * to query page for.
482
- */
483
- async $(selector) {
484
- return this.mainFrame().$(selector);
485
- }
486
- /**
487
- * @remarks
488
- *
489
- * The only difference between {@link Page.evaluate | page.evaluate} and
490
- * `page.evaluateHandle` is that `evaluateHandle` will return the value
491
- * wrapped in an in-page object.
492
- *
493
- * If the function passed to `page.evaluteHandle` returns a Promise, the
494
- * function will wait for the promise to resolve and return its value.
495
- *
496
- * You can pass a string instead of a function (although functions are
497
- * recommended as they are easier to debug and use with TypeScript):
498
- *
499
- * @example
500
- * ```
501
- * const aHandle = await page.evaluateHandle('document')
502
- * ```
503
- *
504
- * @example
505
- * {@link JSHandle} instances can be passed as arguments to the `pageFunction`:
506
- * ```
507
- * const aHandle = await page.evaluateHandle(() => document.body);
508
- * const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
509
- * console.log(await resultHandle.jsonValue());
510
- * await resultHandle.dispose();
511
- * ```
512
- *
513
- * Most of the time this function returns a {@link JSHandle},
514
- * but if `pageFunction` returns a reference to an element,
515
- * you instead get an {@link ElementHandle} back:
516
- *
517
- * @example
518
- * ```
519
- * const button = await page.evaluateHandle(() => document.querySelector('button'));
520
- * // can call `click` because `button` is an `ElementHandle`
521
- * await button.click();
522
- * ```
523
- *
524
- * The TypeScript definitions assume that `evaluateHandle` returns
525
- * a `JSHandle`, but if you know it's going to return an
526
- * `ElementHandle`, pass it as the generic argument:
527
- *
528
- * ```
529
- * const button = await page.evaluateHandle<ElementHandle>(...);
530
- * ```
531
- *
532
- * @param pageFunction - a function that is run within the page
533
- * @param args - arguments to be passed to the pageFunction
534
- */
535
- async evaluateHandle(pageFunction, ...args) {
536
- const context = await this.mainFrame().executionContext();
537
- return context.evaluateHandle(pageFunction, ...args);
538
- }
539
- /**
540
- * This method iterates the JavaScript heap and finds all objects with the
541
- * given prototype.
542
- *
543
- * @remarks
544
- * Shortcut for
545
- * {@link ExecutionContext.queryObjects |
546
- * page.mainFrame().executionContext().queryObjects(prototypeHandle)}.
547
- *
548
- * @example
549
- *
550
- * ```js
551
- * // Create a Map object
552
- * await page.evaluate(() => window.map = new Map());
553
- * // Get a handle to the Map object prototype
554
- * const mapPrototype = await page.evaluateHandle(() => Map.prototype);
555
- * // Query all map instances into an array
556
- * const mapInstances = await page.queryObjects(mapPrototype);
557
- * // Count amount of map objects in heap
558
- * const count = await page.evaluate(maps => maps.length, mapInstances);
559
- * await mapInstances.dispose();
560
- * await mapPrototype.dispose();
561
- * ```
562
- * @param prototypeHandle - a handle to the object prototype.
563
- * @returns Promise which resolves to a handle to an array of objects with
564
- * this prototype.
565
- */
566
- async queryObjects(prototypeHandle) {
567
- const context = await this.mainFrame().executionContext();
568
- return context.queryObjects(prototypeHandle);
569
- }
570
- /**
571
- * This method runs `document.querySelector` within the page and passes the
572
- * result as the first argument to the `pageFunction`.
573
- *
574
- * @remarks
575
- *
576
- * If no element is found matching `selector`, the method will throw an error.
577
- *
578
- * If `pageFunction` returns a promise `$eval` will wait for the promise to
579
- * resolve and then return its value.
580
- *
581
- * @example
582
- *
583
- * ```
584
- * const searchValue = await page.$eval('#search', el => el.value);
585
- * const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
586
- * const html = await page.$eval('.main-container', el => el.outerHTML);
587
- * ```
588
- *
589
- * If you are using TypeScript, you may have to provide an explicit type to the
590
- * first argument of the `pageFunction`.
591
- * By default it is typed as `Element`, but you may need to provide a more
592
- * specific sub-type:
593
- *
594
- * @example
595
- *
596
- * ```
597
- * // if you don't provide HTMLInputElement here, TS will error
598
- * // as `value` is not on `Element`
599
- * const searchValue = await page.$eval('#search', (el: HTMLInputElement) => el.value);
600
- * ```
601
- *
602
- * The compiler should be able to infer the return type
603
- * from the `pageFunction` you provide. If it is unable to, you can use the generic
604
- * type to tell the compiler what return type you expect from `$eval`:
605
- *
606
- * @example
607
- *
608
- * ```
609
- * // The compiler can infer the return type in this case, but if it can't
610
- * // or if you want to be more explicit, provide it as the generic type.
611
- * const searchValue = await page.$eval<string>(
612
- * '#search', (el: HTMLInputElement) => el.value
613
- * );
614
- * ```
615
- *
616
- * @param selector - the
617
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
618
- * to query for
619
- * @param pageFunction - the function to be evaluated in the page context.
620
- * Will be passed the result of `document.querySelector(selector)` as its
621
- * first argument.
622
- * @param args - any additional arguments to pass through to `pageFunction`.
623
- *
624
- * @returns The result of calling `pageFunction`. If it returns an element it
625
- * is wrapped in an {@link ElementHandle}, else the raw value itself is
626
- * returned.
627
- */
628
- async $eval(selector, pageFunction, ...args) {
629
- return this.mainFrame().$eval(selector, pageFunction, ...args);
630
- }
631
- /**
632
- * This method runs `Array.from(document.querySelectorAll(selector))` within
633
- * the page and passes the result as the first argument to the `pageFunction`.
634
- *
635
- * @remarks
636
- *
637
- * If `pageFunction` returns a promise `$$eval` will wait for the promise to
638
- * resolve and then return its value.
639
- *
640
- * @example
641
- *
642
- * ```
643
- * // get the amount of divs on the page
644
- * const divCount = await page.$$eval('div', divs => divs.length);
645
- *
646
- * // get the text content of all the `.options` elements:
647
- * const options = await page.$$eval('div > span.options', options => {
648
- * return options.map(option => option.textContent)
649
- * });
650
- * ```
651
- *
652
- * If you are using TypeScript, you may have to provide an explicit type to the
653
- * first argument of the `pageFunction`.
654
- * By default it is typed as `Element[]`, but you may need to provide a more
655
- * specific sub-type:
656
- *
657
- * @example
658
- *
659
- * ```
660
- * // if you don't provide HTMLInputElement here, TS will error
661
- * // as `value` is not on `Element`
662
- * await page.$$eval('input', (elements: HTMLInputElement[]) => {
663
- * return elements.map(e => e.value);
664
- * });
665
- * ```
666
- *
667
- * The compiler should be able to infer the return type
668
- * from the `pageFunction` you provide. If it is unable to, you can use the generic
669
- * type to tell the compiler what return type you expect from `$$eval`:
670
- *
671
- * @example
672
- *
673
- * ```
674
- * // The compiler can infer the return type in this case, but if it can't
675
- * // or if you want to be more explicit, provide it as the generic type.
676
- * const allInputValues = await page.$$eval<string[]>(
677
- * 'input', (elements: HTMLInputElement[]) => elements.map(e => e.textContent)
678
- * );
679
- * ```
680
- *
681
- * @param selector - the
682
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
683
- * to query for
684
- * @param pageFunction - the function to be evaluated in the page context. Will
685
- * be passed the result of `Array.from(document.querySelectorAll(selector))`
686
- * as its first argument.
687
- * @param args - any additional arguments to pass through to `pageFunction`.
688
- *
689
- * @returns The result of calling `pageFunction`. If it returns an element it
690
- * is wrapped in an {@link ElementHandle}, else the raw value itself is
691
- * returned.
692
- */
693
- async $$eval(selector, pageFunction, ...args) {
694
- return this.mainFrame().$$eval(selector, pageFunction, ...args);
695
- }
696
- /**
697
- * The method runs `document.querySelectorAll` within the page. If no elements
698
- * match the selector, the return value resolves to `[]`.
699
- * @remarks
700
- * Shortcut for {@link Frame.$$ | Page.mainFrame().$$(selector) }.
701
- * @param selector - A `selector` to query page for
702
- */
703
- async $$(selector) {
704
- return this.mainFrame().$$(selector);
705
- }
706
- /**
707
- * The method evaluates the XPath expression relative to the page document as
708
- * its context node. If there are no such elements, the method resolves to an
709
- * empty array.
710
- * @remarks
711
- * Shortcut for {@link Frame.$x | Page.mainFrame().$x(expression) }.
712
- * @param expression - Expression to evaluate
713
- */
714
- async $x(expression) {
715
- return this.mainFrame().$x(expression);
716
- }
717
- /**
718
- * If no URLs are specified, this method returns cookies for the current page
719
- * URL. If URLs are specified, only cookies for those URLs are returned.
720
- */
721
- async cookies(...urls) {
722
- const originalCookies = (await this._client.send('Network.getCookies', {
723
- urls: urls.length ? urls : [this.url()],
724
- })).cookies;
725
- const unsupportedCookieAttributes = ['priority'];
726
- const filterUnsupportedAttributes = (cookie) => {
727
- for (const attr of unsupportedCookieAttributes)
728
- delete cookie[attr];
729
- return cookie;
730
- };
731
- return originalCookies.map(filterUnsupportedAttributes);
732
- }
733
- async deleteCookie(...cookies) {
734
- const pageURL = this.url();
735
- for (const cookie of cookies) {
736
- const item = Object.assign({}, cookie);
737
- if (!cookie.url && pageURL.startsWith('http'))
738
- item.url = pageURL;
739
- await this._client.send('Network.deleteCookies', item);
740
- }
741
- }
742
- /**
743
- * @example
744
- * ```js
745
- * await page.setCookie(cookieObject1, cookieObject2);
746
- * ```
747
- */
748
- async setCookie(...cookies) {
749
- const pageURL = this.url();
750
- const startsWithHTTP = pageURL.startsWith('http');
751
- const items = cookies.map((cookie) => {
752
- const item = Object.assign({}, cookie);
753
- if (!item.url && startsWithHTTP)
754
- item.url = pageURL;
755
- assert(item.url !== 'about:blank', `Blank page can not have cookie "${item.name}"`);
756
- assert(!String.prototype.startsWith.call(item.url || '', 'data:'), `Data URL page can not have cookie "${item.name}"`);
757
- return item;
758
- });
759
- await this.deleteCookie(...items);
760
- if (items.length)
761
- await this._client.send('Network.setCookies', { cookies: items });
762
- }
763
- /**
764
- * Adds a `<script>` tag into the page with the desired URL or content.
765
- * @remarks
766
- * Shortcut for {@link Frame.addScriptTag | page.mainFrame().addScriptTag(options) }.
767
- * @returns Promise which resolves to the added tag when the script's onload fires or
768
- * when the script content was injected into frame.
769
- */
770
- async addScriptTag(options) {
771
- return this.mainFrame().addScriptTag(options);
772
- }
773
- /**
774
- * Adds a `<link rel="stylesheet">` tag into the page with the desired URL or a
775
- * `<style type="text/css">` tag with the content.
776
- * @returns Promise which resolves to the added tag when the stylesheet's
777
- * onload fires or when the CSS content was injected into frame.
778
- */
779
- async addStyleTag(options) {
780
- return this.mainFrame().addStyleTag(options);
781
- }
782
- /**
783
- * The method adds a function called `name` on the page's `window` object. When
784
- * called, the function executes `puppeteerFunction` in node.js and returns a
785
- * `Promise` which resolves to the return value of `puppeteerFunction`.
786
- *
787
- * If the puppeteerFunction returns a `Promise`, it will be awaited.
788
- *
789
- * NOTE: Functions installed via `page.exposeFunction` survive navigations.
790
- * @param name - Name of the function on the window object
791
- * @param puppeteerFunction - Callback function which will be called in
792
- * Puppeteer's context.
793
- * @example
794
- * An example of adding an `md5` function into the page:
795
- * ```js
796
- * const puppeteer = require('puppeteer');
797
- * const crypto = require('crypto');
798
- *
799
- * (async () => {
800
- * const browser = await puppeteer.launch();
801
- * const page = await browser.newPage();
802
- * page.on('console', (msg) => console.log(msg.text()));
803
- * await page.exposeFunction('md5', (text) =>
804
- * crypto.createHash('md5').update(text).digest('hex')
805
- * );
806
- * await page.evaluate(async () => {
807
- * // use window.md5 to compute hashes
808
- * const myString = 'PUPPETEER';
809
- * const myHash = await window.md5(myString);
810
- * console.log(`md5 of ${myString} is ${myHash}`);
811
- * });
812
- * await browser.close();
813
- * })();
814
- * ```
815
- * An example of adding a `window.readfile` function into the page:
816
- * ```js
817
- * const puppeteer = require('puppeteer');
818
- * const fs = require('fs');
819
- *
820
- * (async () => {
821
- * const browser = await puppeteer.launch();
822
- * const page = await browser.newPage();
823
- * page.on('console', (msg) => console.log(msg.text()));
824
- * await page.exposeFunction('readfile', async (filePath) => {
825
- * return new Promise((resolve, reject) => {
826
- * fs.readFile(filePath, 'utf8', (err, text) => {
827
- * if (err) reject(err);
828
- * else resolve(text);
829
- * });
830
- * });
831
- * });
832
- * await page.evaluate(async () => {
833
- * // use window.readfile to read contents of a file
834
- * const content = await window.readfile('/etc/hosts');
835
- * console.log(content);
836
- * });
837
- * await browser.close();
838
- * })();
839
- * ```
840
- */
841
- async exposeFunction(name, puppeteerFunction) {
842
- if (this._pageBindings.has(name))
843
- throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);
844
- this._pageBindings.set(name, puppeteerFunction);
845
- const expression = helper.pageBindingInitString('exposedFun', name);
846
- await this._client.send('Runtime.addBinding', { name: name });
847
- await this._client.send('Page.addScriptToEvaluateOnNewDocument', {
848
- source: expression,
849
- });
850
- await Promise.all(this.frames().map((frame) => frame.evaluate(expression).catch(debugError)));
851
- }
852
- /**
853
- * Provide credentials for `HTTP authentication`.
854
- * @remarks To disable authentication, pass `null`.
855
- */
856
- async authenticate(credentials) {
857
- return this._frameManager.networkManager().authenticate(credentials);
858
- }
859
- /**
860
- * The extra HTTP headers will be sent with every request the page initiates.
861
- * NOTE: All HTTP header names are lowercased. (HTTP headers are
862
- * case-insensitive, so this shouldn’t impact your server code.)
863
- * NOTE: page.setExtraHTTPHeaders does not guarantee the order of headers in
864
- * the outgoing requests.
865
- * @param headers - An object containing additional HTTP headers to be sent
866
- * with every request. All header values must be strings.
867
- * @returns
868
- */
869
- async setExtraHTTPHeaders(headers) {
870
- return this._frameManager.networkManager().setExtraHTTPHeaders(headers);
871
- }
872
- /**
873
- * @param userAgent - Specific user agent to use in this page
874
- * @param userAgentData - Specific user agent client hint data to use in this
875
- * page
876
- * @returns Promise which resolves when the user agent is set.
877
- */
878
- async setUserAgent(userAgent, userAgentMetadata) {
879
- return this._frameManager
880
- .networkManager()
881
- .setUserAgent(userAgent, userAgentMetadata);
882
- }
883
- /**
884
- * @returns Object containing metrics as key/value pairs.
885
- *
886
- * - `Timestamp` : The timestamp when the metrics sample was taken.
887
- *
888
- * - `Documents` : Number of documents in the page.
889
- *
890
- * - `Frames` : Number of frames in the page.
891
- *
892
- * - `JSEventListeners` : Number of events in the page.
893
- *
894
- * - `Nodes` : Number of DOM nodes in the page.
895
- *
896
- * - `LayoutCount` : Total number of full or partial page layout.
897
- *
898
- * - `RecalcStyleCount` : Total number of page style recalculations.
899
- *
900
- * - `LayoutDuration` : Combined durations of all page layouts.
901
- *
902
- * - `RecalcStyleDuration` : Combined duration of all page style
903
- * recalculations.
904
- *
905
- * - `ScriptDuration` : Combined duration of JavaScript execution.
906
- *
907
- * - `TaskDuration` : Combined duration of all tasks performed by the browser.
908
- *
909
- *
910
- * - `JSHeapUsedSize` : Used JavaScript heap size.
911
- *
912
- * - `JSHeapTotalSize` : Total JavaScript heap size.
913
- * @remarks
914
- * NOTE: All timestamps are in monotonic time: monotonically increasing time
915
- * in seconds since an arbitrary point in the past.
916
- */
917
- async metrics() {
918
- const response = await this._client.send('Performance.getMetrics');
919
- return this._buildMetricsObject(response.metrics);
920
- }
921
- _emitMetrics(event) {
922
- this.emit("metrics" /* Metrics */, {
923
- title: event.title,
924
- metrics: this._buildMetricsObject(event.metrics),
925
- });
926
- }
927
- _buildMetricsObject(metrics) {
928
- const result = {};
929
- for (const metric of metrics || []) {
930
- if (supportedMetrics.has(metric.name))
931
- result[metric.name] = metric.value;
932
- }
933
- return result;
934
- }
935
- _handleException(exceptionDetails) {
936
- const message = helper.getExceptionMessage(exceptionDetails);
937
- const err = new Error(message);
938
- err.stack = ''; // Don't report clientside error with a node stack attached
939
- this.emit("pageerror" /* PageError */, err);
940
- }
941
- async _onConsoleAPI(event) {
942
- if (event.executionContextId === 0) {
943
- // DevTools protocol stores the last 1000 console messages. These
944
- // messages are always reported even for removed execution contexts. In
945
- // this case, they are marked with executionContextId = 0 and are
946
- // reported upon enabling Runtime agent.
947
- //
948
- // Ignore these messages since:
949
- // - there's no execution context we can use to operate with message
950
- // arguments
951
- // - these messages are reported before Puppeteer clients can subscribe
952
- // to the 'console'
953
- // page event.
954
- //
955
- // @see https://github.com/puppeteer/puppeteer/issues/3865
956
- return;
957
- }
958
- const context = this._frameManager.executionContextById(event.executionContextId);
959
- const values = event.args.map((arg) => createJSHandle(context, arg));
960
- this._addConsoleMessage(event.type, values, event.stackTrace);
961
- }
962
- async _onBindingCalled(event) {
963
- let payload;
964
- try {
965
- payload = JSON.parse(event.payload);
966
- }
967
- catch {
968
- // The binding was either called by something in the page or it was
969
- // called before our wrapper was initialized.
970
- return;
971
- }
972
- const { type, name, seq, args } = payload;
973
- if (type !== 'exposedFun' || !this._pageBindings.has(name))
974
- return;
975
- let expression = null;
976
- try {
977
- const result = await this._pageBindings.get(name)(...args);
978
- expression = helper.pageBindingDeliverResultString(name, seq, result);
979
- }
980
- catch (error) {
981
- if (error instanceof Error)
982
- expression = helper.pageBindingDeliverErrorString(name, seq, error.message, error.stack);
983
- else
984
- expression = helper.pageBindingDeliverErrorValueString(name, seq, error);
985
- }
986
- this._client
987
- .send('Runtime.evaluate', {
988
- expression,
989
- contextId: event.executionContextId,
990
- })
991
- .catch(debugError);
992
- }
993
- _addConsoleMessage(type, args, stackTrace) {
994
- if (!this.listenerCount("console" /* Console */)) {
995
- args.forEach((arg) => arg.dispose());
996
- return;
997
- }
998
- const textTokens = [];
999
- for (const arg of args) {
1000
- const remoteObject = arg._remoteObject;
1001
- if (remoteObject.objectId)
1002
- textTokens.push(arg.toString());
1003
- else
1004
- textTokens.push(helper.valueFromRemoteObject(remoteObject));
1005
- }
1006
- const stackTraceLocations = [];
1007
- if (stackTrace) {
1008
- for (const callFrame of stackTrace.callFrames) {
1009
- stackTraceLocations.push({
1010
- url: callFrame.url,
1011
- lineNumber: callFrame.lineNumber,
1012
- columnNumber: callFrame.columnNumber,
1013
- });
1014
- }
1015
- }
1016
- const message = new ConsoleMessage(type, textTokens.join(' '), args, stackTraceLocations);
1017
- this.emit("console" /* Console */, message);
1018
- }
1019
- _onDialog(event) {
1020
- let dialogType = null;
1021
- const validDialogTypes = new Set([
1022
- 'alert',
1023
- 'confirm',
1024
- 'prompt',
1025
- 'beforeunload',
1026
- ]);
1027
- if (validDialogTypes.has(event.type)) {
1028
- dialogType = event.type;
1029
- }
1030
- assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
1031
- const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt);
1032
- this.emit("dialog" /* Dialog */, dialog);
1033
- }
1034
- /**
1035
- * Resets default white background
1036
- */
1037
- async _resetDefaultBackgroundColor() {
1038
- await this._client.send('Emulation.setDefaultBackgroundColorOverride');
1039
- }
1040
- /**
1041
- * Hides default white background
1042
- */
1043
- async _setTransparentBackgroundColor() {
1044
- await this._client.send('Emulation.setDefaultBackgroundColorOverride', {
1045
- color: { r: 0, g: 0, b: 0, a: 0 },
1046
- });
1047
- }
1048
- /**
1049
- *
1050
- * @returns
1051
- * @remarks Shortcut for
1052
- * {@link Frame.url | page.mainFrame().url()}.
1053
- */
1054
- url() {
1055
- return this.mainFrame().url();
1056
- }
1057
- async content() {
1058
- return await this._frameManager.mainFrame().content();
1059
- }
1060
- /**
1061
- * @param html - HTML markup to assign to the page.
1062
- * @param options - Parameters that has some properties.
1063
- * @remarks
1064
- * The parameter `options` might have the following options.
1065
- *
1066
- * - `timeout` : Maximum time in milliseconds for resources to load, defaults
1067
- * to 30 seconds, pass `0` to disable timeout. The default value can be
1068
- * changed by using the
1069
- * {@link Page.setDefaultNavigationTimeout |
1070
- * page.setDefaultNavigationTimeout(timeout)}
1071
- * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1072
- * methods.
1073
- *
1074
- * - `waitUntil`: When to consider setting markup succeeded, defaults to `load`.
1075
- * Given an array of event strings, setting content is considered to be
1076
- * successful after all events have been fired. Events can be either:<br/>
1077
- * - `load` : consider setting content to be finished when the `load` event is
1078
- * fired.<br/>
1079
- * - `domcontentloaded` : consider setting content to be finished when the
1080
- * `DOMContentLoaded` event is fired.<br/>
1081
- * - `networkidle0` : consider setting content to be finished when there are no
1082
- * more than 0 network connections for at least `500` ms.<br/>
1083
- * - `networkidle2` : consider setting content to be finished when there are no
1084
- * more than 2 network connections for at least `500` ms.
1085
- */
1086
- async setContent(html, options = {}) {
1087
- await this._frameManager.mainFrame().setContent(html, options);
1088
- }
1089
- /**
1090
- * @param url - URL to navigate page to. The URL should include scheme, e.g.
1091
- * `https://`
1092
- * @param options - Navigation Parameter
1093
- * @returns Promise which resolves to the main resource response. In case of
1094
- * multiple redirects, the navigation will resolve with the response of the
1095
- * last redirect.
1096
- * @remarks
1097
- * The argument `options` might have the following properties:
1098
- *
1099
- * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
1100
- * seconds, pass 0 to disable timeout. The default value can be changed by
1101
- * using the
1102
- * {@link Page.setDefaultNavigationTimeout |
1103
- * page.setDefaultNavigationTimeout(timeout)}
1104
- * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1105
- * methods.
1106
- *
1107
- * - `waitUntil`:When to consider navigation succeeded, defaults to `load`.
1108
- * Given an array of event strings, navigation is considered to be successful
1109
- * after all events have been fired. Events can be either:<br/>
1110
- * - `load` : consider navigation to be finished when the load event is
1111
- * fired.<br/>
1112
- * - `domcontentloaded` : consider navigation to be finished when the
1113
- * DOMContentLoaded event is fired.<br/>
1114
- * - `networkidle0` : consider navigation to be finished when there are no
1115
- * more than 0 network connections for at least `500` ms.<br/>
1116
- * - `networkidle2` : consider navigation to be finished when there are no
1117
- * more than 2 network connections for at least `500` ms.
1118
- *
1119
- * - `referer` : Referer header value. If provided it will take preference
1120
- * over the referer header value set by
1121
- * {@link Page.setExtraHTTPHeaders |page.setExtraHTTPHeaders()}.
1122
- *
1123
- * `page.goto` will throw an error if:
1124
- * - there's an SSL error (e.g. in case of self-signed certificates).
1125
- * - target URL is invalid.
1126
- * - the timeout is exceeded during navigation.
1127
- * - the remote server does not respond or is unreachable.
1128
- * - the main resource failed to load.
1129
- *
1130
- * `page.goto` will not throw an error when any valid HTTP status code is
1131
- * returned by the remote server, including 404 "Not Found" and 500
1132
- * "Internal Server Error". The status code for such responses can be
1133
- * retrieved by calling response.status().
1134
- *
1135
- * NOTE: `page.goto` either throws an error or returns a main resource
1136
- * response. The only exceptions are navigation to about:blank or navigation
1137
- * to the same URL with a different hash, which would succeed and return null.
1138
- *
1139
- * NOTE: Headless mode doesn't support navigation to a PDF document. See the
1140
- * {@link https://bugs.chromium.org/p/chromium/issues/detail?id=761295
1141
- * | upstream issue}.
1142
- *
1143
- * Shortcut for {@link Frame.goto | page.mainFrame().goto(url, options)}.
1144
- */
1145
- async goto(url, options = {}) {
1146
- return await this._frameManager.mainFrame().goto(url, options);
1147
- }
1148
- /**
1149
- * @param options - Navigation parameters which might have the following
1150
- * properties:
1151
- * @returns Promise which resolves to the main resource response. In case of
1152
- * multiple redirects, the navigation will resolve with the response of the
1153
- * last redirect.
1154
- * @remarks
1155
- * The argument `options` might have the following properties:
1156
- *
1157
- * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
1158
- * seconds, pass 0 to disable timeout. The default value can be changed by
1159
- * using the
1160
- * {@link Page.setDefaultNavigationTimeout |
1161
- * page.setDefaultNavigationTimeout(timeout)}
1162
- * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1163
- * methods.
1164
- *
1165
- * - `waitUntil`: When to consider navigation succeeded, defaults to `load`.
1166
- * Given an array of event strings, navigation is considered to be
1167
- * successful after all events have been fired. Events can be either:<br/>
1168
- * - `load` : consider navigation to be finished when the load event is fired.<br/>
1169
- * - `domcontentloaded` : consider navigation to be finished when the
1170
- * DOMContentLoaded event is fired.<br/>
1171
- * - `networkidle0` : consider navigation to be finished when there are no
1172
- * more than 0 network connections for at least `500` ms.<br/>
1173
- * - `networkidle2` : consider navigation to be finished when there are no
1174
- * more than 2 network connections for at least `500` ms.
1175
- */
1176
- async reload(options) {
1177
- const result = await Promise.all([
1178
- this.waitForNavigation(options),
1179
- this._client.send('Page.reload'),
1180
- ]);
1181
- return result[0];
1182
- }
1183
- /**
1184
- * This resolves when the page navigates to a new URL or reloads. It is useful
1185
- * when you run code that will indirectly cause the page to navigate. Consider
1186
- * this example:
1187
- * ```js
1188
- * const [response] = await Promise.all([
1189
- * page.waitForNavigation(), // The promise resolves after navigation has finished
1190
- * page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
1191
- * ]);
1192
- * ```
1193
- *
1194
- * @param options - Navigation parameters which might have the following properties:
1195
- * @returns Promise which resolves to the main resource response. In case of
1196
- * multiple redirects, the navigation will resolve with the response of the
1197
- * last redirect. In case of navigation to a different anchor or navigation
1198
- * due to History API usage, the navigation will resolve with `null`.
1199
- * @remarks
1200
- * NOTE: Usage of the
1201
- * {@link https://developer.mozilla.org/en-US/docs/Web/API/History_API | History API}
1202
- * to change the URL is considered a navigation.
1203
- *
1204
- * Shortcut for
1205
- * {@link Frame.waitForNavigation | page.mainFrame().waitForNavigation(options)}.
1206
- */
1207
- async waitForNavigation(options = {}) {
1208
- return await this._frameManager.mainFrame().waitForNavigation(options);
1209
- }
1210
- _sessionClosePromise() {
1211
- if (!this._disconnectPromise)
1212
- this._disconnectPromise = new Promise((fulfill) => this._client.once(CDPSessionEmittedEvents.Disconnected, () => fulfill(new Error('Target closed'))));
1213
- return this._disconnectPromise;
1214
- }
1215
- /**
1216
- * @param urlOrPredicate - A URL or predicate to wait for
1217
- * @param options - Optional waiting parameters
1218
- * @returns Promise which resolves to the matched response
1219
- * @example
1220
- * ```js
1221
- * const firstResponse = await page.waitForResponse(
1222
- * 'https://example.com/resource'
1223
- * );
1224
- * const finalResponse = await page.waitForResponse(
1225
- * (response) =>
1226
- * response.url() === 'https://example.com' && response.status() === 200
1227
- * );
1228
- * const finalResponse = await page.waitForResponse(async (response) => {
1229
- * return (await response.text()).includes('<html>');
1230
- * });
1231
- * return finalResponse.ok();
1232
- * ```
1233
- * @remarks
1234
- * Optional Waiting Parameters have:
1235
- *
1236
- * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds, pass
1237
- * `0` to disable the timeout. The default value can be changed by using the
1238
- * {@link Page.setDefaultTimeout} method.
1239
- */
1240
- async waitForRequest(urlOrPredicate, options = {}) {
1241
- const { timeout = this._timeoutSettings.timeout() } = options;
1242
- return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEmittedEvents.Request, (request) => {
1243
- if (helper.isString(urlOrPredicate))
1244
- return urlOrPredicate === request.url();
1245
- if (typeof urlOrPredicate === 'function')
1246
- return !!urlOrPredicate(request);
1247
- return false;
1248
- }, timeout, this._sessionClosePromise());
1249
- }
1250
- /**
1251
- * @param urlOrPredicate - A URL or predicate to wait for.
1252
- * @param options - Optional waiting parameters
1253
- * @returns Promise which resolves to the matched response.
1254
- * @example
1255
- * ```js
1256
- * const firstResponse = await page.waitForResponse(
1257
- * 'https://example.com/resource'
1258
- * );
1259
- * const finalResponse = await page.waitForResponse(
1260
- * (response) =>
1261
- * response.url() === 'https://example.com' && response.status() === 200
1262
- * );
1263
- * const finalResponse = await page.waitForResponse(async (response) => {
1264
- * return (await response.text()).includes('<html>');
1265
- * });
1266
- * return finalResponse.ok();
1267
- * ```
1268
- * @remarks
1269
- * Optional Parameter have:
1270
- *
1271
- * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds,
1272
- * pass `0` to disable the timeout. The default value can be changed by using
1273
- * the {@link Page.setDefaultTimeout} method.
1274
- */
1275
- async waitForResponse(urlOrPredicate, options = {}) {
1276
- const { timeout = this._timeoutSettings.timeout() } = options;
1277
- return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEmittedEvents.Response, async (response) => {
1278
- if (helper.isString(urlOrPredicate))
1279
- return urlOrPredicate === response.url();
1280
- if (typeof urlOrPredicate === 'function')
1281
- return !!(await urlOrPredicate(response));
1282
- return false;
1283
- }, timeout, this._sessionClosePromise());
1284
- }
1285
- /**
1286
- * This method navigate to the previous page in history.
1287
- * @param options - Navigation parameters
1288
- * @returns Promise which resolves to the main resource response. In case of
1289
- * multiple redirects, the navigation will resolve with the response of the
1290
- * last redirect. If can not go back, resolves to `null`.
1291
- * @remarks
1292
- * The argument `options` might have the following properties:
1293
- *
1294
- * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
1295
- * seconds, pass 0 to disable timeout. The default value can be changed by
1296
- * using the
1297
- * {@link Page.setDefaultNavigationTimeout
1298
- * | page.setDefaultNavigationTimeout(timeout)}
1299
- * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1300
- * methods.
1301
- *
1302
- * - `waitUntil` : When to consider navigation succeeded, defaults to `load`.
1303
- * Given an array of event strings, navigation is considered to be
1304
- * successful after all events have been fired. Events can be either:<br/>
1305
- * - `load` : consider navigation to be finished when the load event is fired.<br/>
1306
- * - `domcontentloaded` : consider navigation to be finished when the
1307
- * DOMContentLoaded event is fired.<br/>
1308
- * - `networkidle0` : consider navigation to be finished when there are no
1309
- * more than 0 network connections for at least `500` ms.<br/>
1310
- * - `networkidle2` : consider navigation to be finished when there are no
1311
- * more than 2 network connections for at least `500` ms.
1312
- */
1313
- async goBack(options = {}) {
1314
- return this._go(-1, options);
1315
- }
1316
- /**
1317
- * This method navigate to the next page in history.
1318
- * @param options - Navigation Parameter
1319
- * @returns Promise which resolves to the main resource response. In case of
1320
- * multiple redirects, the navigation will resolve with the response of the
1321
- * last redirect. If can not go forward, resolves to `null`.
1322
- * @remarks
1323
- * The argument `options` might have the following properties:
1324
- *
1325
- * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
1326
- * seconds, pass 0 to disable timeout. The default value can be changed by
1327
- * using the
1328
- * {@link Page.setDefaultNavigationTimeout
1329
- * | page.setDefaultNavigationTimeout(timeout)}
1330
- * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1331
- * methods.
1332
- *
1333
- * - `waitUntil`: When to consider navigation succeeded, defaults to `load`.
1334
- * Given an array of event strings, navigation is considered to be
1335
- * successful after all events have been fired. Events can be either:<br/>
1336
- * - `load` : consider navigation to be finished when the load event is fired.<br/>
1337
- * - `domcontentloaded` : consider navigation to be finished when the
1338
- * DOMContentLoaded event is fired.<br/>
1339
- * - `networkidle0` : consider navigation to be finished when there are no
1340
- * more than 0 network connections for at least `500` ms.<br/>
1341
- * - `networkidle2` : consider navigation to be finished when there are no
1342
- * more than 2 network connections for at least `500` ms.
1343
- */
1344
- async goForward(options = {}) {
1345
- return this._go(+1, options);
1346
- }
1347
- async _go(delta, options) {
1348
- const history = await this._client.send('Page.getNavigationHistory');
1349
- const entry = history.entries[history.currentIndex + delta];
1350
- if (!entry)
1351
- return null;
1352
- const result = await Promise.all([
1353
- this.waitForNavigation(options),
1354
- this._client.send('Page.navigateToHistoryEntry', { entryId: entry.id }),
1355
- ]);
1356
- return result[0];
1357
- }
1358
- /**
1359
- * Brings page to front (activates tab).
1360
- */
1361
- async bringToFront() {
1362
- await this._client.send('Page.bringToFront');
1363
- }
1364
- /**
1365
- * Emulates given device metrics and user agent. This method is a shortcut for
1366
- * calling two methods: {@link Page.setUserAgent} and {@link Page.setViewport}
1367
- * To aid emulation, Puppeteer provides a list of device descriptors that can
1368
- * be obtained via the {@link Puppeteer.devices} `page.emulate` will resize
1369
- * the page. A lot of websites don't expect phones to change size, so you
1370
- * should emulate before navigating to the page.
1371
- * @example
1372
- * ```js
1373
- * const puppeteer = require('puppeteer');
1374
- * const iPhone = puppeteer.devices['iPhone 6'];
1375
- * (async () => {
1376
- * const browser = await puppeteer.launch();
1377
- * const page = await browser.newPage();
1378
- * await page.emulate(iPhone);
1379
- * await page.goto('https://www.google.com');
1380
- * // other actions...
1381
- * await browser.close();
1382
- * })();
1383
- * ```
1384
- * @remarks List of all available devices is available in the source code:
1385
- * {@link https://github.com/puppeteer/puppeteer/blob/main/src/common/DeviceDescriptors.ts | src/common/DeviceDescriptors.ts}.
1386
- */
1387
- async emulate(options) {
1388
- await Promise.all([
1389
- this.setViewport(options.viewport),
1390
- this.setUserAgent(options.userAgent),
1391
- ]);
1392
- }
1393
- /**
1394
- * @param enabled - Whether or not to enable JavaScript on the page.
1395
- * @returns
1396
- * @remarks
1397
- * NOTE: changing this value won't affect scripts that have already been run.
1398
- * It will take full effect on the next navigation.
1399
- */
1400
- async setJavaScriptEnabled(enabled) {
1401
- if (this._javascriptEnabled === enabled)
1402
- return;
1403
- this._javascriptEnabled = enabled;
1404
- await this._client.send('Emulation.setScriptExecutionDisabled', {
1405
- value: !enabled,
1406
- });
1407
- }
1408
- /**
1409
- * Toggles bypassing page's Content-Security-Policy.
1410
- * @param enabled - sets bypassing of page's Content-Security-Policy.
1411
- * @remarks
1412
- * NOTE: CSP bypassing happens at the moment of CSP initialization rather than
1413
- * evaluation. Usually, this means that `page.setBypassCSP` should be called
1414
- * before navigating to the domain.
1415
- */
1416
- async setBypassCSP(enabled) {
1417
- await this._client.send('Page.setBypassCSP', { enabled });
1418
- }
1419
- /**
1420
- * @param type - Changes the CSS media type of the page. The only allowed
1421
- * values are `screen`, `print` and `null`. Passing `null` disables CSS media
1422
- * emulation.
1423
- * @example
1424
- * ```
1425
- * await page.evaluate(() => matchMedia('screen').matches);
1426
- * // → true
1427
- * await page.evaluate(() => matchMedia('print').matches);
1428
- * // → false
1429
- *
1430
- * await page.emulateMediaType('print');
1431
- * await page.evaluate(() => matchMedia('screen').matches);
1432
- * // false
1433
- * await page.evaluate(() => matchMedia('print').matches);
1434
- * // true
1435
- *
1436
- * await page.emulateMediaType(null);
1437
- * await page.evaluate(() => matchMedia('screen').matches);
1438
- * // true
1439
- * await page.evaluate(() => matchMedia('print').matches);
1440
- * // → false
1441
- * ```
1442
- */
1443
- async emulateMediaType(type) {
1444
- assert(type === 'screen' || type === 'print' || type === null, 'Unsupported media type: ' + type);
1445
- await this._client.send('Emulation.setEmulatedMedia', {
1446
- media: type || '',
1447
- });
1448
- }
1449
- async emulateCPUThrottling(factor) {
1450
- assert(factor === null || factor >= 1, 'Throttling rate should be greater or equal to 1');
1451
- await this._client.send('Emulation.setCPUThrottlingRate', {
1452
- rate: factor !== null ? factor : 1,
1453
- });
1454
- }
1455
- /**
1456
- * @param features - `<?Array<Object>>` Given an array of media feature
1457
- * objects, emulates CSS media features on the page. Each media feature object
1458
- * must have the following properties:
1459
- * @example
1460
- * ```js
1461
- * await page.emulateMediaFeatures([
1462
- * { name: 'prefers-color-scheme', value: 'dark' },
1463
- * ]);
1464
- * await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
1465
- * // true
1466
- * await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
1467
- * // false
1468
- *
1469
- * await page.emulateMediaFeatures([
1470
- * { name: 'prefers-reduced-motion', value: 'reduce' },
1471
- * ]);
1472
- * await page.evaluate(
1473
- * () => matchMedia('(prefers-reduced-motion: reduce)').matches
1474
- * );
1475
- * // → true
1476
- * await page.evaluate(
1477
- * () => matchMedia('(prefers-reduced-motion: no-preference)').matches
1478
- * );
1479
- * // → false
1480
- *
1481
- * await page.emulateMediaFeatures([
1482
- * { name: 'prefers-color-scheme', value: 'dark' },
1483
- * { name: 'prefers-reduced-motion', value: 'reduce' },
1484
- * ]);
1485
- * await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
1486
- * // → true
1487
- * await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
1488
- * // → false
1489
- * await page.evaluate(
1490
- * () => matchMedia('(prefers-reduced-motion: reduce)').matches
1491
- * );
1492
- * // → true
1493
- * await page.evaluate(
1494
- * () => matchMedia('(prefers-reduced-motion: no-preference)').matches
1495
- * );
1496
- * // → false
1497
- *
1498
- * await page.emulateMediaFeatures([{ name: 'color-gamut', value: 'p3' }]);
1499
- * await page.evaluate(() => matchMedia('(color-gamut: srgb)').matches);
1500
- * // → true
1501
- * await page.evaluate(() => matchMedia('(color-gamut: p3)').matches);
1502
- * // → true
1503
- * await page.evaluate(() => matchMedia('(color-gamut: rec2020)').matches);
1504
- * // → false
1505
- * ```
1506
- */
1507
- async emulateMediaFeatures(features) {
1508
- if (features === null)
1509
- await this._client.send('Emulation.setEmulatedMedia', { features: null });
1510
- if (Array.isArray(features)) {
1511
- features.every((mediaFeature) => {
1512
- const name = mediaFeature.name;
1513
- assert(/^(?:prefers-(?:color-scheme|reduced-motion)|color-gamut)$/.test(name), 'Unsupported media feature: ' + name);
1514
- return true;
1515
- });
1516
- await this._client.send('Emulation.setEmulatedMedia', {
1517
- features: features,
1518
- });
1519
- }
1520
- }
1521
- /**
1522
- * @param timezoneId - Changes the timezone of the page. See
1523
- * {@link https://source.chromium.org/chromium/chromium/deps/icu.git/+/faee8bc70570192d82d2978a71e2a615788597d1:source/data/misc/metaZones.txt | ICU’s metaZones.txt}
1524
- * for a list of supported timezone IDs. Passing
1525
- * `null` disables timezone emulation.
1526
- */
1527
- async emulateTimezone(timezoneId) {
1528
- try {
1529
- await this._client.send('Emulation.setTimezoneOverride', {
1530
- timezoneId: timezoneId || '',
1531
- });
1532
- }
1533
- catch (error) {
1534
- if (error.message.includes('Invalid timezone'))
1535
- throw new Error(`Invalid timezone ID: ${timezoneId}`);
1536
- throw error;
1537
- }
1538
- }
1539
- /**
1540
- * Emulates the idle state.
1541
- * If no arguments set, clears idle state emulation.
1542
- *
1543
- * @example
1544
- * ```js
1545
- * // set idle emulation
1546
- * await page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});
1547
- *
1548
- * // do some checks here
1549
- * ...
1550
- *
1551
- * // clear idle emulation
1552
- * await page.emulateIdleState();
1553
- * ```
1554
- *
1555
- * @param overrides - Mock idle state. If not set, clears idle overrides
1556
- */
1557
- async emulateIdleState(overrides) {
1558
- if (overrides) {
1559
- await this._client.send('Emulation.setIdleOverride', {
1560
- isUserActive: overrides.isUserActive,
1561
- isScreenUnlocked: overrides.isScreenUnlocked,
1562
- });
1563
- }
1564
- else {
1565
- await this._client.send('Emulation.clearIdleOverride');
1566
- }
1567
- }
1568
- /**
1569
- * Simulates the given vision deficiency on the page.
1570
- *
1571
- * @example
1572
- * ```js
1573
- * const puppeteer = require('puppeteer');
1574
- *
1575
- * (async () => {
1576
- * const browser = await puppeteer.launch();
1577
- * const page = await browser.newPage();
1578
- * await page.goto('https://v8.dev/blog/10-years');
1579
- *
1580
- * await page.emulateVisionDeficiency('achromatopsia');
1581
- * await page.screenshot({ path: 'achromatopsia.png' });
1582
- *
1583
- * await page.emulateVisionDeficiency('deuteranopia');
1584
- * await page.screenshot({ path: 'deuteranopia.png' });
1585
- *
1586
- * await page.emulateVisionDeficiency('blurredVision');
1587
- * await page.screenshot({ path: 'blurred-vision.png' });
1588
- *
1589
- * await browser.close();
1590
- * })();
1591
- * ```
1592
- *
1593
- * @param type - the type of deficiency to simulate, or `'none'` to reset.
1594
- */
1595
- async emulateVisionDeficiency(type) {
1596
- const visionDeficiencies = new Set([
1597
- 'none',
1598
- 'achromatopsia',
1599
- 'blurredVision',
1600
- 'deuteranopia',
1601
- 'protanopia',
1602
- 'tritanopia',
1603
- ]);
1604
- try {
1605
- assert(!type || visionDeficiencies.has(type), `Unsupported vision deficiency: ${type}`);
1606
- await this._client.send('Emulation.setEmulatedVisionDeficiency', {
1607
- type: type || 'none',
1608
- });
1609
- }
1610
- catch (error) {
1611
- throw error;
1612
- }
1613
- }
1614
- /**
1615
- * `page.setViewport` will resize the page. A lot of websites don't expect
1616
- * phones to change size, so you should set the viewport before navigating to
1617
- * the page.
1618
- *
1619
- * In the case of multiple pages in a single browser, each page can have its
1620
- * own viewport size.
1621
- * @example
1622
- * ```js
1623
- * const page = await browser.newPage();
1624
- * await page.setViewport({
1625
- * width: 640,
1626
- * height: 480,
1627
- * deviceScaleFactor: 1,
1628
- * });
1629
- * await page.goto('https://example.com');
1630
- * ```
1631
- *
1632
- * @param viewport -
1633
- * @remarks
1634
- * Argument viewport have following properties:
1635
- *
1636
- * - `width`: page width in pixels. required
1637
- *
1638
- * - `height`: page height in pixels. required
1639
- *
1640
- * - `deviceScaleFactor`: Specify device scale factor (can be thought of as
1641
- * DPR). Defaults to `1`.
1642
- *
1643
- * - `isMobile`: Whether the meta viewport tag is taken into account. Defaults
1644
- * to `false`.
1645
- *
1646
- * - `hasTouch`: Specifies if viewport supports touch events. Defaults to `false`
1647
- *
1648
- * - `isLandScape`: Specifies if viewport is in landscape mode. Defaults to false.
1649
- *
1650
- * NOTE: in certain cases, setting viewport will reload the page in order to
1651
- * set the isMobile or hasTouch properties.
1652
- */
1653
- async setViewport(viewport) {
1654
- const needsReload = await this._emulationManager.emulateViewport(viewport);
1655
- this._viewport = viewport;
1656
- if (needsReload)
1657
- await this.reload();
1658
- }
1659
- /**
1660
- * @returns
1661
- *
1662
- * - `width`: page's width in pixels
1663
- *
1664
- * - `height`: page's height in pixels
1665
- *
1666
- * - `deviceScalarFactor`: Specify device scale factor (can be though of as
1667
- * dpr). Defaults to `1`.
1668
- *
1669
- * - `isMobile`: Whether the meta viewport tag is taken into account. Defaults
1670
- * to `false`.
1671
- *
1672
- * - `hasTouch`: Specifies if viewport supports touch events. Defaults to
1673
- * `false`.
1674
- *
1675
- * - `isLandScape`: Specifies if viewport is in landscape mode. Defaults to
1676
- * `false`.
1677
- */
1678
- viewport() {
1679
- return this._viewport;
1680
- }
1681
- /**
1682
- * @remarks
1683
- *
1684
- * Evaluates a function in the page's context and returns the result.
1685
- *
1686
- * If the function passed to `page.evaluteHandle` returns a Promise, the
1687
- * function will wait for the promise to resolve and return its value.
1688
- *
1689
- * @example
1690
- *
1691
- * ```js
1692
- * const result = await frame.evaluate(() => {
1693
- * return Promise.resolve(8 * 7);
1694
- * });
1695
- * console.log(result); // prints "56"
1696
- * ```
1697
- *
1698
- * You can pass a string instead of a function (although functions are
1699
- * recommended as they are easier to debug and use with TypeScript):
1700
- *
1701
- * @example
1702
- * ```
1703
- * const aHandle = await page.evaluate('1 + 2');
1704
- * ```
1705
- *
1706
- * To get the best TypeScript experience, you should pass in as the
1707
- * generic the type of `pageFunction`:
1708
- *
1709
- * ```
1710
- * const aHandle = await page.evaluate<() => number>(() => 2);
1711
- * ```
1712
- *
1713
- * @example
1714
- *
1715
- * {@link ElementHandle} instances (including {@link JSHandle}s) can be passed
1716
- * as arguments to the `pageFunction`:
1717
- *
1718
- * ```
1719
- * const bodyHandle = await page.$('body');
1720
- * const html = await page.evaluate(body => body.innerHTML, bodyHandle);
1721
- * await bodyHandle.dispose();
1722
- * ```
1723
- *
1724
- * @param pageFunction - a function that is run within the page
1725
- * @param args - arguments to be passed to the pageFunction
1726
- *
1727
- * @returns the return value of `pageFunction`.
1728
- */
1729
- async evaluate(pageFunction, ...args) {
1730
- return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
1731
- }
1732
- /**
1733
- * Adds a function which would be invoked in one of the following scenarios:
1734
- *
1735
- * - whenever the page is navigated
1736
- *
1737
- * - whenever the child frame is attached or navigated. In this case, the
1738
- * function is invoked in the context of the newly attached frame.
1739
- *
1740
- * The function is invoked after the document was created but before any of
1741
- * its scripts were run. This is useful to amend the JavaScript environment,
1742
- * e.g. to seed `Math.random`.
1743
- * @param pageFunction - Function to be evaluated in browser context
1744
- * @param args - Arguments to pass to `pageFunction`
1745
- * @example
1746
- * An example of overriding the navigator.languages property before the page loads:
1747
- * ```js
1748
- * // preload.js
1749
- *
1750
- * // overwrite the `languages` property to use a custom getter
1751
- * Object.defineProperty(navigator, 'languages', {
1752
- * get: function () {
1753
- * return ['en-US', 'en', 'bn'];
1754
- * },
1755
- * });
1756
- *
1757
- * // In your puppeteer script, assuming the preload.js file is
1758
- * in same folder of our script
1759
- * const preloadFile = fs.readFileSync('./preload.js', 'utf8');
1760
- * await page.evaluateOnNewDocument(preloadFile);
1761
- * ```
1762
- */
1763
- async evaluateOnNewDocument(pageFunction, ...args) {
1764
- const source = helper.evaluationString(pageFunction, ...args);
1765
- await this._client.send('Page.addScriptToEvaluateOnNewDocument', {
1766
- source,
1767
- });
1768
- }
1769
- /**
1770
- * Toggles ignoring cache for each request based on the enabled state. By
1771
- * default, caching is enabled.
1772
- * @param enabled - sets the `enabled` state of cache
1773
- */
1774
- async setCacheEnabled(enabled = true) {
1775
- await this._frameManager.networkManager().setCacheEnabled(enabled);
1776
- }
1777
- /**
1778
- * @remarks
1779
- * Options object which might have the following properties:
1780
- *
1781
- * - `path` : The file path to save the image to. The screenshot type
1782
- * will be inferred from file extension. If `path` is a relative path, then
1783
- * it is resolved relative to
1784
- * {@link https://nodejs.org/api/process.html#process_process_cwd
1785
- * | current working directory}.
1786
- * If no path is provided, the image won't be saved to the disk.
1787
- *
1788
- * - `type` : Specify screenshot type, can be either `jpeg` or `png`.
1789
- * Defaults to 'png'.
1790
- *
1791
- * - `quality` : The quality of the image, between 0-100. Not
1792
- * applicable to `png` images.
1793
- *
1794
- * - `fullPage` : When true, takes a screenshot of the full
1795
- * scrollable page. Defaults to `false`
1796
- *
1797
- * - `clip` : An object which specifies clipping region of the page.
1798
- * Should have the following fields:<br/>
1799
- * - `x` : x-coordinate of top-left corner of clip area.<br/>
1800
- * - `y` : y-coordinate of top-left corner of clip area.<br/>
1801
- * - `width` : width of clipping area.<br/>
1802
- * - `height` : height of clipping area.
1803
- *
1804
- * - `omitBackground` : Hides default white background and allows
1805
- * capturing screenshots with transparency. Defaults to `false`
1806
- *
1807
- * - `encoding` : The encoding of the image, can be either base64 or
1808
- * binary. Defaults to `binary`.
1809
- *
1810
- *
1811
- * NOTE: Screenshots take at least 1/6 second on OS X. See
1812
- * {@link https://crbug.com/741689} for discussion.
1813
- * @returns Promise which resolves to buffer or a base64 string (depending on
1814
- * the value of `encoding`) with captured screenshot.
1815
- */
1816
- async screenshot(options = {}) {
1817
- let screenshotType = null;
1818
- // options.type takes precedence over inferring the type from options.path
1819
- // because it may be a 0-length file with no extension created beforehand
1820
- // (i.e. as a temp file).
1821
- if (options.type) {
1822
- assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type);
1823
- screenshotType = options.type;
1824
- }
1825
- else if (options.path) {
1826
- const filePath = options.path;
1827
- const extension = filePath
1828
- .slice(filePath.lastIndexOf('.') + 1)
1829
- .toLowerCase();
1830
- if (extension === 'png')
1831
- screenshotType = 'png';
1832
- else if (extension === 'jpg' || extension === 'jpeg')
1833
- screenshotType = 'jpeg';
1834
- assert(screenshotType, `Unsupported screenshot type for extension \`.${extension}\``);
1835
- }
1836
- if (!screenshotType)
1837
- screenshotType = 'png';
1838
- if (options.quality) {
1839
- assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' +
1840
- screenshotType +
1841
- ' screenshots');
1842
- assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' +
1843
- typeof options.quality);
1844
- assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');
1845
- assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' +
1846
- options.quality);
1847
- }
1848
- assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');
1849
- if (options.clip) {
1850
- assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' +
1851
- typeof options.clip.x);
1852
- assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' +
1853
- typeof options.clip.y);
1854
- assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' +
1855
- typeof options.clip.width);
1856
- assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' +
1857
- typeof options.clip.height);
1858
- assert(options.clip.width !== 0, 'Expected options.clip.width not to be 0.');
1859
- assert(options.clip.height !== 0, 'Expected options.clip.height not to be 0.');
1860
- }
1861
- return this._screenshotTaskQueue.postTask(() => this._screenshotTask(screenshotType, options));
1862
- }
1863
- async _screenshotTask(format, options) {
1864
- await this._client.send('Target.activateTarget', {
1865
- targetId: this._target._targetId,
1866
- });
1867
- let clip = options.clip ? processClip(options.clip) : undefined;
1868
- let { captureBeyondViewport = true } = options;
1869
- captureBeyondViewport =
1870
- typeof captureBeyondViewport === 'boolean' ? captureBeyondViewport : true;
1871
- if (options.fullPage) {
1872
- const metrics = await this._client.send('Page.getLayoutMetrics');
1873
- // Fallback to `contentSize` in case of using Firefox.
1874
- const { width, height } = metrics.cssContentSize || metrics.contentSize;
1875
- // Overwrite clip for full page.
1876
- clip = { x: 0, y: 0, width, height, scale: 1 };
1877
- if (!captureBeyondViewport) {
1878
- const { isMobile = false, deviceScaleFactor = 1, isLandscape = false, } = this._viewport || {};
1879
- const screenOrientation = isLandscape
1880
- ? { angle: 90, type: 'landscapePrimary' }
1881
- : { angle: 0, type: 'portraitPrimary' };
1882
- await this._client.send('Emulation.setDeviceMetricsOverride', {
1883
- mobile: isMobile,
1884
- width,
1885
- height,
1886
- deviceScaleFactor,
1887
- screenOrientation,
1888
- });
1889
- }
1890
- }
1891
- const shouldSetDefaultBackground = options.omitBackground && format === 'png';
1892
- if (shouldSetDefaultBackground) {
1893
- await this._setTransparentBackgroundColor();
1894
- }
1895
- const result = await this._client.send('Page.captureScreenshot', {
1896
- format,
1897
- quality: options.quality,
1898
- clip,
1899
- captureBeyondViewport,
1900
- });
1901
- if (shouldSetDefaultBackground) {
1902
- await this._resetDefaultBackgroundColor();
1903
- }
1904
- if (options.fullPage && this._viewport)
1905
- await this.setViewport(this._viewport);
1906
- const buffer = options.encoding === 'base64'
1907
- ? result.data
1908
- : Buffer.from(result.data, 'base64');
1909
- if (options.path) {
1910
- if (!isNode) {
1911
- throw new Error('Screenshots can only be written to a file path in a Node environment.');
1912
- }
1913
- const fs = await helper.importFSModule();
1914
- await fs.promises.writeFile(options.path, buffer);
1915
- }
1916
- return buffer;
1917
- function processClip(clip) {
1918
- const x = Math.round(clip.x);
1919
- const y = Math.round(clip.y);
1920
- const width = Math.round(clip.width + clip.x - x);
1921
- const height = Math.round(clip.height + clip.y - y);
1922
- return { x, y, width, height, scale: 1 };
1923
- }
1924
- }
1925
- /**
1926
- * Generatees a PDF of the page with the `print` CSS media type.
1927
- * @remarks
1928
- *
1929
- * NOTE: PDF generation is only supported in Chrome headless mode.
1930
- *
1931
- * To generate a PDF with the `screen` media type, call
1932
- * {@link Page.emulateMediaType | `page.emulateMediaType('screen')`} before
1933
- * calling `page.pdf()`.
1934
- *
1935
- * By default, `page.pdf()` generates a pdf with modified colors for printing.
1936
- * Use the
1937
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust | `-webkit-print-color-adjust`}
1938
- * property to force rendering of exact colors.
1939
- *
1940
- *
1941
- * @param options - options for generating the PDF.
1942
- */
1943
- async createPDFStream(options = {}) {
1944
- const { scale = 1, displayHeaderFooter = false, headerTemplate = '', footerTemplate = '', printBackground = false, landscape = false, pageRanges = '', preferCSSPageSize = false, margin = {}, omitBackground = false, } = options;
1945
- let paperWidth = 8.5;
1946
- let paperHeight = 11;
1947
- if (options.format) {
1948
- const format = paperFormats[options.format.toLowerCase()];
1949
- assert(format, 'Unknown paper format: ' + options.format);
1950
- paperWidth = format.width;
1951
- paperHeight = format.height;
1952
- }
1953
- else {
1954
- paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
1955
- paperHeight =
1956
- convertPrintParameterToInches(options.height) || paperHeight;
1957
- }
1958
- const marginTop = convertPrintParameterToInches(margin.top) || 0;
1959
- const marginLeft = convertPrintParameterToInches(margin.left) || 0;
1960
- const marginBottom = convertPrintParameterToInches(margin.bottom) || 0;
1961
- const marginRight = convertPrintParameterToInches(margin.right) || 0;
1962
- if (omitBackground) {
1963
- await this._setTransparentBackgroundColor();
1964
- }
1965
- const result = await this._client.send('Page.printToPDF', {
1966
- transferMode: 'ReturnAsStream',
1967
- landscape,
1968
- displayHeaderFooter,
1969
- headerTemplate,
1970
- footerTemplate,
1971
- printBackground,
1972
- scale,
1973
- paperWidth,
1974
- paperHeight,
1975
- marginTop,
1976
- marginBottom,
1977
- marginLeft,
1978
- marginRight,
1979
- pageRanges,
1980
- preferCSSPageSize,
1981
- });
1982
- if (omitBackground) {
1983
- await this._resetDefaultBackgroundColor();
1984
- }
1985
- return helper.getReadableFromProtocolStream(this._client, result.stream);
1986
- }
1987
- /**
1988
- * @param options -
1989
- * @returns
1990
- */
1991
- async pdf(options = {}) {
1992
- const { path = undefined } = options;
1993
- const readable = await this.createPDFStream(options);
1994
- return await helper.getReadableAsBuffer(readable, path);
1995
- }
1996
- /**
1997
- * @returns The page's title
1998
- * @remarks
1999
- * Shortcut for {@link Frame.title | page.mainFrame().title()}.
2000
- */
2001
- async title() {
2002
- return this.mainFrame().title();
2003
- }
2004
- async close(options = { runBeforeUnload: undefined }) {
2005
- assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');
2006
- const runBeforeUnload = !!options.runBeforeUnload;
2007
- if (runBeforeUnload) {
2008
- await this._client.send('Page.close');
2009
- }
2010
- else {
2011
- await this._client._connection.send('Target.closeTarget', {
2012
- targetId: this._target._targetId,
2013
- });
2014
- await this._target._isClosedPromise;
2015
- }
2016
- }
2017
- /**
2018
- * Indicates that the page has been closed.
2019
- * @returns
2020
- */
2021
- isClosed() {
2022
- return this._closed;
2023
- }
2024
- get mouse() {
2025
- return this._mouse;
2026
- }
2027
- /**
2028
- * This method fetches an element with `selector`, scrolls it into view if
2029
- * needed, and then uses {@link Page.mouse} to click in the center of the
2030
- * element. If there's no element matching `selector`, the method throws an
2031
- * error.
2032
- * @remarks Bear in mind that if `click()` triggers a navigation event and
2033
- * there's a separate `page.waitForNavigation()` promise to be resolved, you
2034
- * may end up with a race condition that yields unexpected results. The
2035
- * correct pattern for click and wait for navigation is the following:
2036
- * ```js
2037
- * const [response] = await Promise.all([
2038
- * page.waitForNavigation(waitOptions),
2039
- * page.click(selector, clickOptions),
2040
- * ]);
2041
- * ```
2042
- * Shortcut for {@link Frame.click | page.mainFrame().click(selector[, options]) }.
2043
- * @param selector - A `selector` to search for element to click. If there are
2044
- * multiple elements satisfying the `selector`, the first will be clicked
2045
- * @param options - `Object`
2046
- * @returns Promise which resolves when the element matching `selector` is
2047
- * successfully clicked. The Promise will be rejected if there is no element
2048
- * matching `selector`.
2049
- */
2050
- click(selector, options = {}) {
2051
- return this.mainFrame().click(selector, options);
2052
- }
2053
- /**
2054
- * This method fetches an element with `selector` and focuses it. If there's no
2055
- * element matching `selector`, the method throws an error.
2056
- * @param selector - A
2057
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector }
2058
- * of an element to focus. If there are multiple elements satisfying the
2059
- * selector, the first will be focused.
2060
- * @returns Promise which resolves when the element matching selector is
2061
- * successfully focused. The promise will be rejected if there is no element
2062
- * matching selector.
2063
- * @remarks
2064
- * Shortcut for {@link Frame.focus | page.mainFrame().focus(selector)}.
2065
- */
2066
- focus(selector) {
2067
- return this.mainFrame().focus(selector);
2068
- }
2069
- /**
2070
- * This method fetches an element with `selector`, scrolls it into view if
2071
- * needed, and then uses {@link Page.mouse} to hover over the center of the element.
2072
- * If there's no element matching `selector`, the method throws an error.
2073
- * @param selector - A
2074
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
2075
- * to search for element to hover. If there are multiple elements satisfying
2076
- * the selector, the first will be hovered.
2077
- * @returns Promise which resolves when the element matching `selector` is
2078
- * successfully hovered. Promise gets rejected if there's no element matching
2079
- * `selector`.
2080
- * @remarks
2081
- * Shortcut for {@link Page.hover | page.mainFrame().hover(selector)}.
2082
- */
2083
- hover(selector) {
2084
- return this.mainFrame().hover(selector);
2085
- }
2086
- /**
2087
- * Triggers a `change` and `input` event once all the provided options have been
2088
- * selected. If there's no `<select>` element matching `selector`, the method
2089
- * throws an error.
2090
- *
2091
- * @example
2092
- * ```js
2093
- * page.select('select#colors', 'blue'); // single selection
2094
- * page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
2095
- * ```
2096
- * @param selector - A
2097
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | Selector}
2098
- * to query the page for
2099
- * @param values - Values of options to select. If the `<select>` has the
2100
- * `multiple` attribute, all values are considered, otherwise only the first one
2101
- * is taken into account.
2102
- * @returns
2103
- *
2104
- * @remarks
2105
- * Shortcut for {@link Frame.select | page.mainFrame().select()}
2106
- */
2107
- select(selector, ...values) {
2108
- return this.mainFrame().select(selector, ...values);
2109
- }
2110
- /**
2111
- * This method fetches an element with `selector`, scrolls it into view if
2112
- * needed, and then uses {@link Page.touchscreen} to tap in the center of the element.
2113
- * If there's no element matching `selector`, the method throws an error.
2114
- * @param selector - A
2115
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | Selector}
2116
- * to search for element to tap. If there are multiple elements satisfying the
2117
- * selector, the first will be tapped.
2118
- * @returns
2119
- * @remarks
2120
- * Shortcut for {@link Frame.tap | page.mainFrame().tap(selector)}.
2121
- */
2122
- tap(selector) {
2123
- return this.mainFrame().tap(selector);
2124
- }
2125
- /**
2126
- * Sends a `keydown`, `keypress/input`, and `keyup` event for each character
2127
- * in the text.
2128
- *
2129
- * To press a special key, like `Control` or `ArrowDown`, use {@link Keyboard.press}.
2130
- * @example
2131
- * ```
2132
- * await page.type('#mytextarea', 'Hello');
2133
- * // Types instantly
2134
- * await page.type('#mytextarea', 'World', { delay: 100 });
2135
- * // Types slower, like a user
2136
- * ```
2137
- * @param selector - A
2138
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
2139
- * of an element to type into. If there are multiple elements satisfying the
2140
- * selector, the first will be used.
2141
- * @param text - A text to type into a focused element.
2142
- * @param options - have property `delay` which is the Time to wait between
2143
- * key presses in milliseconds. Defaults to `0`.
2144
- * @returns
2145
- * @remarks
2146
- */
2147
- type(selector, text, options) {
2148
- return this.mainFrame().type(selector, text, options);
2149
- }
2150
- /**
2151
- * @remarks
2152
- *
2153
- * This method behaves differently depending on the first parameter. If it's a
2154
- * `string`, it will be treated as a `selector` or `xpath` (if the string
2155
- * starts with `//`). This method then is a shortcut for
2156
- * {@link Page.waitForSelector} or {@link Page.waitForXPath}.
2157
- *
2158
- * If the first argument is a function this method is a shortcut for
2159
- * {@link Page.waitForFunction}.
2160
- *
2161
- * If the first argument is a `number`, it's treated as a timeout in
2162
- * milliseconds and the method returns a promise which resolves after the
2163
- * timeout.
2164
- *
2165
- * @param selectorOrFunctionOrTimeout - a selector, predicate or timeout to
2166
- * wait for.
2167
- * @param options - optional waiting parameters.
2168
- * @param args - arguments to pass to `pageFunction`.
2169
- *
2170
- * @deprecated Don't use this method directly. Instead use the more explicit
2171
- * methods available: {@link Page.waitForSelector},
2172
- * {@link Page.waitForXPath}, {@link Page.waitForFunction} or
2173
- * {@link Page.waitForTimeout}.
2174
- */
2175
- waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
2176
- return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
2177
- }
2178
- /**
2179
- * Causes your script to wait for the given number of milliseconds.
2180
- *
2181
- * @remarks
2182
- *
2183
- * It's generally recommended to not wait for a number of seconds, but instead
2184
- * use {@link Page.waitForSelector}, {@link Page.waitForXPath} or
2185
- * {@link Page.waitForFunction} to wait for exactly the conditions you want.
2186
- *
2187
- * @example
2188
- *
2189
- * Wait for 1 second:
2190
- *
2191
- * ```
2192
- * await page.waitForTimeout(1000);
2193
- * ```
2194
- *
2195
- * @param milliseconds - the number of milliseconds to wait.
2196
- */
2197
- waitForTimeout(milliseconds) {
2198
- return this.mainFrame().waitForTimeout(milliseconds);
2199
- }
2200
- /**
2201
- * Wait for the `selector` to appear in page. If at the moment of calling the
2202
- * method the `selector` already exists, the method will return immediately. If
2203
- * the `selector` doesn't appear after the `timeout` milliseconds of waiting, the
2204
- * function will throw.
2205
- *
2206
- * This method works across navigations:
2207
- * ```js
2208
- * const puppeteer = require('puppeteer');
2209
- * (async () => {
2210
- * const browser = await puppeteer.launch();
2211
- * const page = await browser.newPage();
2212
- * let currentURL;
2213
- * page
2214
- * .waitForSelector('img')
2215
- * .then(() => console.log('First URL with image: ' + currentURL));
2216
- * for (currentURL of [
2217
- * 'https://example.com',
2218
- * 'https://google.com',
2219
- * 'https://bbc.com',
2220
- * ]) {
2221
- * await page.goto(currentURL);
2222
- * }
2223
- * await browser.close();
2224
- * })();
2225
- * ```
2226
- * @param selector - A
2227
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
2228
- * of an element to wait for
2229
- * @param options - Optional waiting parameters
2230
- * @returns Promise which resolves when element specified by selector string
2231
- * is added to DOM. Resolves to `null` if waiting for hidden: `true` and
2232
- * selector is not found in DOM.
2233
- * @remarks
2234
- * The optional Parameter in Arguments `options` are :
2235
- *
2236
- * - `Visible`: A boolean wait for element to be present in DOM and to be
2237
- * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
2238
- * properties. Defaults to `false`.
2239
- *
2240
- * - `hidden`: ait for element to not be found in the DOM or to be hidden,
2241
- * i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to
2242
- * `false`.
2243
- *
2244
- * - `timeout`: maximum time to wait for in milliseconds. Defaults to `30000`
2245
- * (30 seconds). Pass `0` to disable timeout. The default value can be changed
2246
- * by using the {@link Page.setDefaultTimeout} method.
2247
- */
2248
- waitForSelector(selector, options = {}) {
2249
- return this.mainFrame().waitForSelector(selector, options);
2250
- }
2251
- /**
2252
- * Wait for the `xpath` to appear in page. If at the moment of calling the
2253
- * method the `xpath` already exists, the method will return immediately. If
2254
- * the `xpath` doesn't appear after the `timeout` milliseconds of waiting, the
2255
- * function will throw.
2256
- *
2257
- * This method works across navigation
2258
- * ```js
2259
- * const puppeteer = require('puppeteer');
2260
- * (async () => {
2261
- * const browser = await puppeteer.launch();
2262
- * const page = await browser.newPage();
2263
- * let currentURL;
2264
- * page
2265
- * .waitForXPath('//img')
2266
- * .then(() => console.log('First URL with image: ' + currentURL));
2267
- * for (currentURL of [
2268
- * 'https://example.com',
2269
- * 'https://google.com',
2270
- * 'https://bbc.com',
2271
- * ]) {
2272
- * await page.goto(currentURL);
2273
- * }
2274
- * await browser.close();
2275
- * })();
2276
- * ```
2277
- * @param xpath - A
2278
- * {@link https://developer.mozilla.org/en-US/docs/Web/XPath | xpath} of an
2279
- * element to wait for
2280
- * @param options - Optional waiting parameters
2281
- * @returns Promise which resolves when element specified by xpath string is
2282
- * added to DOM. Resolves to `null` if waiting for `hidden: true` and xpath is
2283
- * not found in DOM.
2284
- * @remarks
2285
- * The optional Argument `options` have properties:
2286
- *
2287
- * - `visible`: A boolean to wait for element to be present in DOM and to be
2288
- * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
2289
- * properties. Defaults to `false`.
2290
- *
2291
- * - `hidden`: A boolean wait for element to not be found in the DOM or to be
2292
- * hidden, i.e. have `display: none` or `visibility: hidden` CSS properties.
2293
- * Defaults to `false`.
2294
- *
2295
- * - `timeout`: A number which is maximum time to wait for in milliseconds.
2296
- * Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default
2297
- * value can be changed by using the {@link Page.setDefaultTimeout} method.
2298
- */
2299
- waitForXPath(xpath, options = {}) {
2300
- return this.mainFrame().waitForXPath(xpath, options);
2301
- }
2302
- /**
2303
- * The `waitForFunction` can be used to observe viewport size change:
2304
- *
2305
- * ```
2306
- * const puppeteer = require('puppeteer');
2307
- * (async () => {
2308
- * const browser = await puppeteer.launch();
2309
- * const page = await browser.newPage();
2310
- * const watchDog = page.waitForFunction('window.innerWidth < 100');
2311
- * await page.setViewport({ width: 50, height: 50 });
2312
- * await watchDog;
2313
- * await browser.close();
2314
- * })();
2315
- * ```
2316
- * To pass arguments from node.js to the predicate of `page.waitForFunction` function:
2317
- * ```
2318
- * const selector = '.foo';
2319
- * await page.waitForFunction(
2320
- * (selector) => !!document.querySelector(selector),
2321
- * {},
2322
- * selector
2323
- * );
2324
- * ```
2325
- * The predicate of `page.waitForFunction` can be asynchronous too:
2326
- * ```
2327
- * const username = 'github-username';
2328
- * await page.waitForFunction(
2329
- * async (username) => {
2330
- * const githubResponse = await fetch(
2331
- * `https://api.github.com/users/${username}`
2332
- * );
2333
- * const githubUser = await githubResponse.json();
2334
- * // show the avatar
2335
- * const img = document.createElement('img');
2336
- * img.src = githubUser.avatar_url;
2337
- * // wait 3 seconds
2338
- * await new Promise((resolve, reject) => setTimeout(resolve, 3000));
2339
- * img.remove();
2340
- * },
2341
- * {},
2342
- * username
2343
- * );
2344
- * ```
2345
- * @param pageFunction - Function to be evaluated in browser context
2346
- * @param options - Optional waiting parameters
2347
- * @param args - Arguments to pass to `pageFunction`
2348
- * @returns Promise which resolves when the `pageFunction` returns a truthy
2349
- * value. It resolves to a JSHandle of the truthy value.
2350
- *
2351
- * The optional waiting parameter can be:
2352
- *
2353
- * - `Polling`: An interval at which the `pageFunction` is executed, defaults to
2354
- * `raf`. If `polling` is a number, then it is treated as an interval in
2355
- * milliseconds at which the function would be executed. If polling is a
2356
- * string, then it can be one of the following values:<br/>
2357
- * - `raf`: to constantly execute `pageFunction` in `requestAnimationFrame`
2358
- * callback. This is the tightest polling mode which is suitable to
2359
- * observe styling changes.<br/>
2360
- * - `mutation`: to execute pageFunction on every DOM mutation.
2361
- *
2362
- * - `timeout`: maximum time to wait for in milliseconds. Defaults to `30000`
2363
- * (30 seconds). Pass `0` to disable timeout. The default value can be changed
2364
- * by using the
2365
- * {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)} method.
2366
- *
2367
- */
2368
- waitForFunction(pageFunction, options = {}, ...args) {
2369
- return this.mainFrame().waitForFunction(pageFunction, options, ...args);
2370
- }
2371
- }
2372
- const supportedMetrics = new Set([
2373
- 'Timestamp',
2374
- 'Documents',
2375
- 'Frames',
2376
- 'JSEventListeners',
2377
- 'Nodes',
2378
- 'LayoutCount',
2379
- 'RecalcStyleCount',
2380
- 'LayoutDuration',
2381
- 'RecalcStyleDuration',
2382
- 'ScriptDuration',
2383
- 'TaskDuration',
2384
- 'JSHeapUsedSize',
2385
- 'JSHeapTotalSize',
2386
- ]);
2387
- const unitToPixels = {
2388
- px: 1,
2389
- in: 96,
2390
- cm: 37.8,
2391
- mm: 3.78,
2392
- };
2393
- function convertPrintParameterToInches(parameter) {
2394
- if (typeof parameter === 'undefined')
2395
- return undefined;
2396
- let pixels;
2397
- if (helper.isNumber(parameter)) {
2398
- // Treat numbers as pixel values to be aligned with phantom's paperSize.
2399
- pixels = /** @type {number} */ parameter;
2400
- }
2401
- else if (helper.isString(parameter)) {
2402
- const text = /** @type {string} */ parameter;
2403
- let unit = text.substring(text.length - 2).toLowerCase();
2404
- let valueText = '';
2405
- if (unitToPixels.hasOwnProperty(unit)) {
2406
- valueText = text.substring(0, text.length - 2);
2407
- }
2408
- else {
2409
- // In case of unknown unit try to parse the whole parameter as number of pixels.
2410
- // This is consistent with phantom's paperSize behavior.
2411
- unit = 'px';
2412
- valueText = text;
2413
- }
2414
- const value = Number(valueText);
2415
- assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
2416
- pixels = value * unitToPixels[unit];
2417
- }
2418
- else {
2419
- throw new Error('page.pdf() Cannot handle parameter type: ' + typeof parameter);
2420
- }
2421
- return pixels / 96;
2422
- }
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
+ */
16
+ import { EventEmitter } from './EventEmitter.js';
17
+ import { Connection, CDPSessionEmittedEvents, } from './Connection.js';
18
+ import { Dialog } from './Dialog.js';
19
+ import { EmulationManager } from './EmulationManager.js';
20
+ import { FrameManager, FrameManagerEmittedEvents, } from './FrameManager.js';
21
+ import { Keyboard, Mouse, Touchscreen } from './Input.js';
22
+ import { Tracing } from './Tracing.js';
23
+ import { assert, assertNever } from './assert.js';
24
+ import { helper, debugError } from './helper.js';
25
+ import { Coverage } from './Coverage.js';
26
+ import { WebWorker } from './WebWorker.js';
27
+ import { createJSHandle } from './JSHandle.js';
28
+ import { NetworkManagerEmittedEvents, } from './NetworkManager.js';
29
+ import { Accessibility } from './Accessibility.js';
30
+ import { TimeoutSettings } from './TimeoutSettings.js';
31
+ import { FileChooser } from './FileChooser.js';
32
+ import { ConsoleMessage } from './ConsoleMessage.js';
33
+ import { paperFormats } from './PDFOptions.js';
34
+ import { isNode } from '../environment.js';
35
+ /**
36
+ * Page provides methods to interact with a single tab or
37
+ * {@link https://developer.chrome.com/extensions/background_pages | extension background page} in Chromium.
38
+ *
39
+ * @remarks
40
+ *
41
+ * One Browser instance might have multiple Page instances.
42
+ *
43
+ * @example
44
+ * This example creates a page, navigates it to a URL, and then * saves a screenshot:
45
+ * ```js
46
+ * const puppeteer = require('puppeteer');
47
+ *
48
+ * (async () => {
49
+ * const browser = await puppeteer.launch();
50
+ * const page = await browser.newPage();
51
+ * await page.goto('https://example.com');
52
+ * await page.screenshot({path: 'screenshot.png'});
53
+ * await browser.close();
54
+ * })();
55
+ * ```
56
+ *
57
+ * The Page class extends from Puppeteer's {@link EventEmitter} class and will
58
+ * emit various events which are documented in the {@link PageEmittedEvents} enum.
59
+ *
60
+ * @example
61
+ * This example logs a message for a single page `load` event:
62
+ * ```js
63
+ * page.once('load', () => console.log('Page loaded!'));
64
+ * ```
65
+ *
66
+ * To unsubscribe from events use the `off` method:
67
+ *
68
+ * ```js
69
+ * function logRequest(interceptedRequest) {
70
+ * console.log('A request was made:', interceptedRequest.url());
71
+ * }
72
+ * page.on('request', logRequest);
73
+ * // Sometime later...
74
+ * page.off('request', logRequest);
75
+ * ```
76
+ * @public
77
+ */
78
+ export class Page extends EventEmitter {
79
+ /**
80
+ * @internal
81
+ */
82
+ constructor(client, target, ignoreHTTPSErrors, screenshotTaskQueue) {
83
+ super();
84
+ this._closed = false;
85
+ this._timeoutSettings = new TimeoutSettings();
86
+ this._pageBindings = new Map();
87
+ this._javascriptEnabled = true;
88
+ this._workers = new Map();
89
+ // TODO: improve this typedef - it's a function that takes a file chooser or
90
+ // something?
91
+ this._fileChooserInterceptors = new Set();
92
+ this._userDragInterceptionEnabled = false;
93
+ this._handlerMap = new WeakMap();
94
+ this._client = client;
95
+ this._target = target;
96
+ this._keyboard = new Keyboard(client);
97
+ this._mouse = new Mouse(client, this._keyboard);
98
+ this._touchscreen = new Touchscreen(client, this._keyboard);
99
+ this._accessibility = new Accessibility(client);
100
+ this._frameManager = new FrameManager(client, this, ignoreHTTPSErrors, this._timeoutSettings);
101
+ this._emulationManager = new EmulationManager(client);
102
+ this._tracing = new Tracing(client);
103
+ this._coverage = new Coverage(client);
104
+ this._screenshotTaskQueue = screenshotTaskQueue;
105
+ this._viewport = null;
106
+ client.on('Target.attachedToTarget', (event) => {
107
+ if (event.targetInfo.type !== 'worker' &&
108
+ event.targetInfo.type !== 'iframe') {
109
+ // If we don't detach from service workers, they will never die.
110
+ // We still want to attach to workers for emitting events.
111
+ // We still want to attach to iframes so sessions may interact with them.
112
+ // We detach from all other types out of an abundance of caution.
113
+ // See https://source.chromium.org/chromium/chromium/src/+/main:content/browser/devtools/devtools_agent_host_impl.cc?ss=chromium&q=f:devtools%20-f:out%20%22::kTypePage%5B%5D%22
114
+ // for the complete list of available types.
115
+ client
116
+ .send('Target.detachFromTarget', {
117
+ sessionId: event.sessionId,
118
+ })
119
+ .catch(debugError);
120
+ return;
121
+ }
122
+ if (event.targetInfo.type === 'worker') {
123
+ const session = Connection.fromSession(client).session(event.sessionId);
124
+ const worker = new WebWorker(session, event.targetInfo.url, this._addConsoleMessage.bind(this), this._handleException.bind(this));
125
+ this._workers.set(event.sessionId, worker);
126
+ this.emit("workercreated" /* WorkerCreated */, worker);
127
+ }
128
+ });
129
+ client.on('Target.detachedFromTarget', (event) => {
130
+ const worker = this._workers.get(event.sessionId);
131
+ if (!worker)
132
+ return;
133
+ this._workers.delete(event.sessionId);
134
+ this.emit("workerdestroyed" /* WorkerDestroyed */, worker);
135
+ });
136
+ this._frameManager.on(FrameManagerEmittedEvents.FrameAttached, (event) => this.emit("frameattached" /* FrameAttached */, event));
137
+ this._frameManager.on(FrameManagerEmittedEvents.FrameDetached, (event) => this.emit("framedetached" /* FrameDetached */, event));
138
+ this._frameManager.on(FrameManagerEmittedEvents.FrameNavigated, (event) => this.emit("framenavigated" /* FrameNavigated */, event));
139
+ const networkManager = this._frameManager.networkManager();
140
+ networkManager.on(NetworkManagerEmittedEvents.Request, (event) => this.emit("request" /* Request */, event));
141
+ networkManager.on(NetworkManagerEmittedEvents.RequestServedFromCache, (event) => this.emit("requestservedfromcache" /* RequestServedFromCache */, event));
142
+ networkManager.on(NetworkManagerEmittedEvents.Response, (event) => this.emit("response" /* Response */, event));
143
+ networkManager.on(NetworkManagerEmittedEvents.RequestFailed, (event) => this.emit("requestfailed" /* RequestFailed */, event));
144
+ networkManager.on(NetworkManagerEmittedEvents.RequestFinished, (event) => this.emit("requestfinished" /* RequestFinished */, event));
145
+ this._fileChooserInterceptors = new Set();
146
+ client.on('Page.domContentEventFired', () => this.emit("domcontentloaded" /* DOMContentLoaded */));
147
+ client.on('Page.loadEventFired', () => this.emit("load" /* Load */));
148
+ client.on('Runtime.consoleAPICalled', (event) => this._onConsoleAPI(event));
149
+ client.on('Runtime.bindingCalled', (event) => this._onBindingCalled(event));
150
+ client.on('Page.javascriptDialogOpening', (event) => this._onDialog(event));
151
+ client.on('Runtime.exceptionThrown', (exception) => this._handleException(exception.exceptionDetails));
152
+ client.on('Inspector.targetCrashed', () => this._onTargetCrashed());
153
+ client.on('Performance.metrics', (event) => this._emitMetrics(event));
154
+ client.on('Log.entryAdded', (event) => this._onLogEntryAdded(event));
155
+ client.on('Page.fileChooserOpened', (event) => this._onFileChooser(event));
156
+ this._target._isClosedPromise.then(() => {
157
+ this.emit("close" /* Close */);
158
+ this._closed = true;
159
+ });
160
+ }
161
+ /**
162
+ * @internal
163
+ */
164
+ static async create(client, target, ignoreHTTPSErrors, defaultViewport, screenshotTaskQueue) {
165
+ const page = new Page(client, target, ignoreHTTPSErrors, screenshotTaskQueue);
166
+ await page._initialize();
167
+ if (defaultViewport)
168
+ await page.setViewport(defaultViewport);
169
+ return page;
170
+ }
171
+ async _initialize() {
172
+ await Promise.all([
173
+ this._frameManager.initialize(),
174
+ this._client.send('Target.setAutoAttach', {
175
+ autoAttach: true,
176
+ waitForDebuggerOnStart: false,
177
+ flatten: true,
178
+ }),
179
+ this._client.send('Performance.enable'),
180
+ this._client.send('Log.enable'),
181
+ ]);
182
+ }
183
+ async _onFileChooser(event) {
184
+ if (!this._fileChooserInterceptors.size)
185
+ return;
186
+ const frame = this._frameManager.frame(event.frameId);
187
+ const context = await frame.executionContext();
188
+ const element = await context._adoptBackendNodeId(event.backendNodeId);
189
+ const interceptors = Array.from(this._fileChooserInterceptors);
190
+ this._fileChooserInterceptors.clear();
191
+ const fileChooser = new FileChooser(element, event);
192
+ for (const interceptor of interceptors)
193
+ interceptor.call(null, fileChooser);
194
+ }
195
+ /**
196
+ * @returns `true` if drag events are being intercepted, `false` otherwise.
197
+ */
198
+ isDragInterceptionEnabled() {
199
+ return this._userDragInterceptionEnabled;
200
+ }
201
+ /**
202
+ * @returns `true` if the page has JavaScript enabled, `false` otherwise.
203
+ */
204
+ isJavaScriptEnabled() {
205
+ return this._javascriptEnabled;
206
+ }
207
+ /**
208
+ * Listen to page events.
209
+ */
210
+ // Note: this method exists to define event typings and handle
211
+ // proper wireup of cooperative request interception. Actual event listening and
212
+ // dispatching is delegated to EventEmitter.
213
+ on(eventName, handler) {
214
+ if (eventName === 'request') {
215
+ const wrap = (event) => {
216
+ event.enqueueInterceptAction(() => handler(event));
217
+ };
218
+ this._handlerMap.set(handler, wrap);
219
+ return super.on(eventName, wrap);
220
+ }
221
+ return super.on(eventName, handler);
222
+ }
223
+ once(eventName, handler) {
224
+ // Note: this method only exists to define the types; we delegate the impl
225
+ // to EventEmitter.
226
+ return super.once(eventName, handler);
227
+ }
228
+ off(eventName, handler) {
229
+ if (eventName === 'request') {
230
+ handler = this._handlerMap.get(handler) || handler;
231
+ }
232
+ return super.off(eventName, handler);
233
+ }
234
+ /**
235
+ * This method is typically coupled with an action that triggers file
236
+ * choosing. The following example clicks a button that issues a file chooser
237
+ * and then responds with `/tmp/myfile.pdf` as if a user has selected this file.
238
+ *
239
+ * ```js
240
+ * const [fileChooser] = await Promise.all([
241
+ * page.waitForFileChooser(),
242
+ * page.click('#upload-file-button'),
243
+ * // some button that triggers file selection
244
+ * ]);
245
+ * await fileChooser.accept(['/tmp/myfile.pdf']);
246
+ * ```
247
+ *
248
+ * NOTE: This must be called before the file chooser is launched. It will not
249
+ * return a currently active file chooser.
250
+ * @param options - Optional waiting parameters
251
+ * @returns Resolves after a page requests a file picker.
252
+ * @remarks
253
+ * NOTE: In non-headless Chromium, this method results in the native file picker
254
+ * dialog `not showing up` for the user.
255
+ */
256
+ async waitForFileChooser(options = {}) {
257
+ if (!this._fileChooserInterceptors.size)
258
+ await this._client.send('Page.setInterceptFileChooserDialog', {
259
+ enabled: true,
260
+ });
261
+ const { timeout = this._timeoutSettings.timeout() } = options;
262
+ let callback;
263
+ const promise = new Promise((x) => (callback = x));
264
+ this._fileChooserInterceptors.add(callback);
265
+ return helper
266
+ .waitWithTimeout(promise, 'waiting for file chooser', timeout)
267
+ .catch((error) => {
268
+ this._fileChooserInterceptors.delete(callback);
269
+ throw error;
270
+ });
271
+ }
272
+ /**
273
+ * Sets the page's geolocation.
274
+ * @remarks
275
+ * NOTE: Consider using {@link BrowserContext.overridePermissions} to grant
276
+ * permissions for the page to read its geolocation.
277
+ * @example
278
+ * ```js
279
+ * await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
280
+ * ```
281
+ */
282
+ async setGeolocation(options) {
283
+ const { longitude, latitude, accuracy = 0 } = options;
284
+ if (longitude < -180 || longitude > 180)
285
+ throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
286
+ if (latitude < -90 || latitude > 90)
287
+ throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
288
+ if (accuracy < 0)
289
+ throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
290
+ await this._client.send('Emulation.setGeolocationOverride', {
291
+ longitude,
292
+ latitude,
293
+ accuracy,
294
+ });
295
+ }
296
+ /**
297
+ * @returns A target this page was created from.
298
+ */
299
+ target() {
300
+ return this._target;
301
+ }
302
+ /**
303
+ * Get the CDP session client the page belongs to.
304
+ * @internal
305
+ */
306
+ client() {
307
+ return this._client;
308
+ }
309
+ /**
310
+ * Get the browser the page belongs to.
311
+ */
312
+ browser() {
313
+ return this._target.browser();
314
+ }
315
+ /**
316
+ * Get the browser context that the page belongs to.
317
+ */
318
+ browserContext() {
319
+ return this._target.browserContext();
320
+ }
321
+ _onTargetCrashed() {
322
+ this.emit('error', new Error('Page crashed!'));
323
+ }
324
+ _onLogEntryAdded(event) {
325
+ const { level, text, args, source, url, lineNumber } = event.entry;
326
+ if (args)
327
+ args.map((arg) => helper.releaseObject(this._client, arg));
328
+ if (source !== 'worker')
329
+ this.emit("console" /* Console */, new ConsoleMessage(level, text, [], [{ url, lineNumber }]));
330
+ }
331
+ /**
332
+ * @returns The page's main frame.
333
+ * @remarks
334
+ * Page is guaranteed to have a main frame which persists during navigations.
335
+ */
336
+ mainFrame() {
337
+ return this._frameManager.mainFrame();
338
+ }
339
+ get keyboard() {
340
+ return this._keyboard;
341
+ }
342
+ get touchscreen() {
343
+ return this._touchscreen;
344
+ }
345
+ get coverage() {
346
+ return this._coverage;
347
+ }
348
+ get tracing() {
349
+ return this._tracing;
350
+ }
351
+ get accessibility() {
352
+ return this._accessibility;
353
+ }
354
+ /**
355
+ * @returns An array of all frames attached to the page.
356
+ */
357
+ frames() {
358
+ return this._frameManager.frames();
359
+ }
360
+ /**
361
+ * @returns all of the dedicated
362
+ * {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API |
363
+ * WebWorkers}
364
+ * associated with the page.
365
+ * @remarks
366
+ * NOTE: This does not contain ServiceWorkers
367
+ */
368
+ workers() {
369
+ return Array.from(this._workers.values());
370
+ }
371
+ /**
372
+ * @param value - Whether to enable request interception.
373
+ *
374
+ * @remarks
375
+ * Activating request interception enables {@link HTTPRequest.abort},
376
+ * {@link HTTPRequest.continue} and {@link HTTPRequest.respond} methods. This
377
+ * provides the capability to modify network requests that are made by a page.
378
+ *
379
+ * Once request interception is enabled, every request will stall unless it's
380
+ * continued, responded or aborted; or completed using the browser cache.
381
+ *
382
+ * @example
383
+ * An example of a naïve request interceptor that aborts all image requests:
384
+ * ```js
385
+ * const puppeteer = require('puppeteer');
386
+ * (async () => {
387
+ * const browser = await puppeteer.launch();
388
+ * const page = await browser.newPage();
389
+ * await page.setRequestInterception(true);
390
+ * page.on('request', interceptedRequest => {
391
+ * if (interceptedRequest.url().endsWith('.png') ||
392
+ * interceptedRequest.url().endsWith('.jpg'))
393
+ * interceptedRequest.abort();
394
+ * else
395
+ * interceptedRequest.continue();
396
+ * });
397
+ * await page.goto('https://example.com');
398
+ * await browser.close();
399
+ * })();
400
+ * ```
401
+ * NOTE: Enabling request interception disables page caching.
402
+ */
403
+ async setRequestInterception(value) {
404
+ return this._frameManager.networkManager().setRequestInterception(value);
405
+ }
406
+ /**
407
+ * @param enabled - Whether to enable drag interception.
408
+ *
409
+ * @remarks
410
+ * Activating drag interception enables the `Input.drag`,
411
+ * methods This provides the capability to capture drag events emitted
412
+ * on the page, which can then be used to simulate drag-and-drop.
413
+ */
414
+ async setDragInterception(enabled) {
415
+ this._userDragInterceptionEnabled = enabled;
416
+ return this._client.send('Input.setInterceptDrags', { enabled });
417
+ }
418
+ /**
419
+ * @param enabled - When `true`, enables offline mode for the page.
420
+ * @remarks
421
+ * NOTE: while this method sets the network connection to offline, it does
422
+ * not change the parameters used in [page.emulateNetworkConditions(networkConditions)]
423
+ * (#pageemulatenetworkconditionsnetworkconditions)
424
+ */
425
+ setOfflineMode(enabled) {
426
+ return this._frameManager.networkManager().setOfflineMode(enabled);
427
+ }
428
+ /**
429
+ * @param networkConditions - Passing `null` disables network condition emulation.
430
+ * @example
431
+ * ```js
432
+ * const puppeteer = require('puppeteer');
433
+ * const slow3G = puppeteer.networkConditions['Slow 3G'];
434
+ *
435
+ * (async () => {
436
+ * const browser = await puppeteer.launch();
437
+ * const page = await browser.newPage();
438
+ * await page.emulateNetworkConditions(slow3G);
439
+ * await page.goto('https://www.google.com');
440
+ * // other actions...
441
+ * await browser.close();
442
+ * })();
443
+ * ```
444
+ * @remarks
445
+ * NOTE: This does not affect WebSockets and WebRTC PeerConnections (see
446
+ * https://crbug.com/563644). To set the page offline, you can use
447
+ * [page.setOfflineMode(enabled)](#pagesetofflinemodeenabled).
448
+ */
449
+ emulateNetworkConditions(networkConditions) {
450
+ return this._frameManager
451
+ .networkManager()
452
+ .emulateNetworkConditions(networkConditions);
453
+ }
454
+ /**
455
+ * This setting will change the default maximum navigation time for the
456
+ * following methods and related shortcuts:
457
+ *
458
+ * - {@link Page.goBack | page.goBack(options)}
459
+ *
460
+ * - {@link Page.goForward | page.goForward(options)}
461
+ *
462
+ * - {@link Page.goto | page.goto(url,options)}
463
+ *
464
+ * - {@link Page.reload | page.reload(options)}
465
+ *
466
+ * - {@link Page.setContent | page.setContent(html,options)}
467
+ *
468
+ * - {@link Page.waitForNavigation | page.waitForNavigation(options)}
469
+ * @param timeout - Maximum navigation time in milliseconds.
470
+ */
471
+ setDefaultNavigationTimeout(timeout) {
472
+ this._timeoutSettings.setDefaultNavigationTimeout(timeout);
473
+ }
474
+ /**
475
+ * @param timeout - Maximum time in milliseconds.
476
+ */
477
+ setDefaultTimeout(timeout) {
478
+ this._timeoutSettings.setDefaultTimeout(timeout);
479
+ }
480
+ /**
481
+ * Runs `document.querySelector` within the page. If no element matches the
482
+ * selector, the return value resolves to `null`.
483
+ *
484
+ * @remarks
485
+ * Shortcut for {@link Frame.$ | Page.mainFrame().$(selector) }.
486
+ *
487
+ * @param selector - A `selector` to query page for
488
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
489
+ * to query page for.
490
+ */
491
+ async $(selector) {
492
+ return this.mainFrame().$(selector);
493
+ }
494
+ /**
495
+ * @remarks
496
+ *
497
+ * The only difference between {@link Page.evaluate | page.evaluate} and
498
+ * `page.evaluateHandle` is that `evaluateHandle` will return the value
499
+ * wrapped in an in-page object.
500
+ *
501
+ * If the function passed to `page.evaluteHandle` returns a Promise, the
502
+ * function will wait for the promise to resolve and return its value.
503
+ *
504
+ * You can pass a string instead of a function (although functions are
505
+ * recommended as they are easier to debug and use with TypeScript):
506
+ *
507
+ * @example
508
+ * ```
509
+ * const aHandle = await page.evaluateHandle('document')
510
+ * ```
511
+ *
512
+ * @example
513
+ * {@link JSHandle} instances can be passed as arguments to the `pageFunction`:
514
+ * ```
515
+ * const aHandle = await page.evaluateHandle(() => document.body);
516
+ * const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
517
+ * console.log(await resultHandle.jsonValue());
518
+ * await resultHandle.dispose();
519
+ * ```
520
+ *
521
+ * Most of the time this function returns a {@link JSHandle},
522
+ * but if `pageFunction` returns a reference to an element,
523
+ * you instead get an {@link ElementHandle} back:
524
+ *
525
+ * @example
526
+ * ```
527
+ * const button = await page.evaluateHandle(() => document.querySelector('button'));
528
+ * // can call `click` because `button` is an `ElementHandle`
529
+ * await button.click();
530
+ * ```
531
+ *
532
+ * The TypeScript definitions assume that `evaluateHandle` returns
533
+ * a `JSHandle`, but if you know it's going to return an
534
+ * `ElementHandle`, pass it as the generic argument:
535
+ *
536
+ * ```
537
+ * const button = await page.evaluateHandle<ElementHandle>(...);
538
+ * ```
539
+ *
540
+ * @param pageFunction - a function that is run within the page
541
+ * @param args - arguments to be passed to the pageFunction
542
+ */
543
+ async evaluateHandle(pageFunction, ...args) {
544
+ const context = await this.mainFrame().executionContext();
545
+ return context.evaluateHandle(pageFunction, ...args);
546
+ }
547
+ /**
548
+ * This method iterates the JavaScript heap and finds all objects with the
549
+ * given prototype.
550
+ *
551
+ * @remarks
552
+ * Shortcut for
553
+ * {@link ExecutionContext.queryObjects |
554
+ * page.mainFrame().executionContext().queryObjects(prototypeHandle)}.
555
+ *
556
+ * @example
557
+ *
558
+ * ```js
559
+ * // Create a Map object
560
+ * await page.evaluate(() => window.map = new Map());
561
+ * // Get a handle to the Map object prototype
562
+ * const mapPrototype = await page.evaluateHandle(() => Map.prototype);
563
+ * // Query all map instances into an array
564
+ * const mapInstances = await page.queryObjects(mapPrototype);
565
+ * // Count amount of map objects in heap
566
+ * const count = await page.evaluate(maps => maps.length, mapInstances);
567
+ * await mapInstances.dispose();
568
+ * await mapPrototype.dispose();
569
+ * ```
570
+ * @param prototypeHandle - a handle to the object prototype.
571
+ * @returns Promise which resolves to a handle to an array of objects with
572
+ * this prototype.
573
+ */
574
+ async queryObjects(prototypeHandle) {
575
+ const context = await this.mainFrame().executionContext();
576
+ return context.queryObjects(prototypeHandle);
577
+ }
578
+ /**
579
+ * This method runs `document.querySelector` within the page and passes the
580
+ * result as the first argument to the `pageFunction`.
581
+ *
582
+ * @remarks
583
+ *
584
+ * If no element is found matching `selector`, the method will throw an error.
585
+ *
586
+ * If `pageFunction` returns a promise `$eval` will wait for the promise to
587
+ * resolve and then return its value.
588
+ *
589
+ * @example
590
+ *
591
+ * ```
592
+ * const searchValue = await page.$eval('#search', el => el.value);
593
+ * const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
594
+ * const html = await page.$eval('.main-container', el => el.outerHTML);
595
+ * ```
596
+ *
597
+ * If you are using TypeScript, you may have to provide an explicit type to the
598
+ * first argument of the `pageFunction`.
599
+ * By default it is typed as `Element`, but you may need to provide a more
600
+ * specific sub-type:
601
+ *
602
+ * @example
603
+ *
604
+ * ```
605
+ * // if you don't provide HTMLInputElement here, TS will error
606
+ * // as `value` is not on `Element`
607
+ * const searchValue = await page.$eval('#search', (el: HTMLInputElement) => el.value);
608
+ * ```
609
+ *
610
+ * The compiler should be able to infer the return type
611
+ * from the `pageFunction` you provide. If it is unable to, you can use the generic
612
+ * type to tell the compiler what return type you expect from `$eval`:
613
+ *
614
+ * @example
615
+ *
616
+ * ```
617
+ * // The compiler can infer the return type in this case, but if it can't
618
+ * // or if you want to be more explicit, provide it as the generic type.
619
+ * const searchValue = await page.$eval<string>(
620
+ * '#search', (el: HTMLInputElement) => el.value
621
+ * );
622
+ * ```
623
+ *
624
+ * @param selector - the
625
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
626
+ * to query for
627
+ * @param pageFunction - the function to be evaluated in the page context.
628
+ * Will be passed the result of `document.querySelector(selector)` as its
629
+ * first argument.
630
+ * @param args - any additional arguments to pass through to `pageFunction`.
631
+ *
632
+ * @returns The result of calling `pageFunction`. If it returns an element it
633
+ * is wrapped in an {@link ElementHandle}, else the raw value itself is
634
+ * returned.
635
+ */
636
+ async $eval(selector, pageFunction, ...args) {
637
+ return this.mainFrame().$eval(selector, pageFunction, ...args);
638
+ }
639
+ /**
640
+ * This method runs `Array.from(document.querySelectorAll(selector))` within
641
+ * the page and passes the result as the first argument to the `pageFunction`.
642
+ *
643
+ * @remarks
644
+ *
645
+ * If `pageFunction` returns a promise `$$eval` will wait for the promise to
646
+ * resolve and then return its value.
647
+ *
648
+ * @example
649
+ *
650
+ * ```
651
+ * // get the amount of divs on the page
652
+ * const divCount = await page.$$eval('div', divs => divs.length);
653
+ *
654
+ * // get the text content of all the `.options` elements:
655
+ * const options = await page.$$eval('div > span.options', options => {
656
+ * return options.map(option => option.textContent)
657
+ * });
658
+ * ```
659
+ *
660
+ * If you are using TypeScript, you may have to provide an explicit type to the
661
+ * first argument of the `pageFunction`.
662
+ * By default it is typed as `Element[]`, but you may need to provide a more
663
+ * specific sub-type:
664
+ *
665
+ * @example
666
+ *
667
+ * ```
668
+ * // if you don't provide HTMLInputElement here, TS will error
669
+ * // as `value` is not on `Element`
670
+ * await page.$$eval('input', (elements: HTMLInputElement[]) => {
671
+ * return elements.map(e => e.value);
672
+ * });
673
+ * ```
674
+ *
675
+ * The compiler should be able to infer the return type
676
+ * from the `pageFunction` you provide. If it is unable to, you can use the generic
677
+ * type to tell the compiler what return type you expect from `$$eval`:
678
+ *
679
+ * @example
680
+ *
681
+ * ```
682
+ * // The compiler can infer the return type in this case, but if it can't
683
+ * // or if you want to be more explicit, provide it as the generic type.
684
+ * const allInputValues = await page.$$eval<string[]>(
685
+ * 'input', (elements: HTMLInputElement[]) => elements.map(e => e.textContent)
686
+ * );
687
+ * ```
688
+ *
689
+ * @param selector - the
690
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
691
+ * to query for
692
+ * @param pageFunction - the function to be evaluated in the page context. Will
693
+ * be passed the result of `Array.from(document.querySelectorAll(selector))`
694
+ * as its first argument.
695
+ * @param args - any additional arguments to pass through to `pageFunction`.
696
+ *
697
+ * @returns The result of calling `pageFunction`. If it returns an element it
698
+ * is wrapped in an {@link ElementHandle}, else the raw value itself is
699
+ * returned.
700
+ */
701
+ async $$eval(selector, pageFunction, ...args) {
702
+ return this.mainFrame().$$eval(selector, pageFunction, ...args);
703
+ }
704
+ /**
705
+ * The method runs `document.querySelectorAll` within the page. If no elements
706
+ * match the selector, the return value resolves to `[]`.
707
+ * @remarks
708
+ * Shortcut for {@link Frame.$$ | Page.mainFrame().$$(selector) }.
709
+ * @param selector - A `selector` to query page for
710
+ */
711
+ async $$(selector) {
712
+ return this.mainFrame().$$(selector);
713
+ }
714
+ /**
715
+ * The method evaluates the XPath expression relative to the page document as
716
+ * its context node. If there are no such elements, the method resolves to an
717
+ * empty array.
718
+ * @remarks
719
+ * Shortcut for {@link Frame.$x | Page.mainFrame().$x(expression) }.
720
+ * @param expression - Expression to evaluate
721
+ */
722
+ async $x(expression) {
723
+ return this.mainFrame().$x(expression);
724
+ }
725
+ /**
726
+ * If no URLs are specified, this method returns cookies for the current page
727
+ * URL. If URLs are specified, only cookies for those URLs are returned.
728
+ */
729
+ async cookies(...urls) {
730
+ const originalCookies = (await this._client.send('Network.getCookies', {
731
+ urls: urls.length ? urls : [this.url()],
732
+ })).cookies;
733
+ const unsupportedCookieAttributes = ['priority'];
734
+ const filterUnsupportedAttributes = (cookie) => {
735
+ for (const attr of unsupportedCookieAttributes)
736
+ delete cookie[attr];
737
+ return cookie;
738
+ };
739
+ return originalCookies.map(filterUnsupportedAttributes);
740
+ }
741
+ async deleteCookie(...cookies) {
742
+ const pageURL = this.url();
743
+ for (const cookie of cookies) {
744
+ const item = Object.assign({}, cookie);
745
+ if (!cookie.url && pageURL.startsWith('http'))
746
+ item.url = pageURL;
747
+ await this._client.send('Network.deleteCookies', item);
748
+ }
749
+ }
750
+ /**
751
+ * @example
752
+ * ```js
753
+ * await page.setCookie(cookieObject1, cookieObject2);
754
+ * ```
755
+ */
756
+ async setCookie(...cookies) {
757
+ const pageURL = this.url();
758
+ const startsWithHTTP = pageURL.startsWith('http');
759
+ const items = cookies.map((cookie) => {
760
+ const item = Object.assign({}, cookie);
761
+ if (!item.url && startsWithHTTP)
762
+ item.url = pageURL;
763
+ assert(item.url !== 'about:blank', `Blank page can not have cookie "${item.name}"`);
764
+ assert(!String.prototype.startsWith.call(item.url || '', 'data:'), `Data URL page can not have cookie "${item.name}"`);
765
+ return item;
766
+ });
767
+ await this.deleteCookie(...items);
768
+ if (items.length)
769
+ await this._client.send('Network.setCookies', { cookies: items });
770
+ }
771
+ /**
772
+ * Adds a `<script>` tag into the page with the desired URL or content.
773
+ * @remarks
774
+ * Shortcut for {@link Frame.addScriptTag | page.mainFrame().addScriptTag(options) }.
775
+ * @returns Promise which resolves to the added tag when the script's onload fires or
776
+ * when the script content was injected into frame.
777
+ */
778
+ async addScriptTag(options) {
779
+ return this.mainFrame().addScriptTag(options);
780
+ }
781
+ /**
782
+ * Adds a `<link rel="stylesheet">` tag into the page with the desired URL or a
783
+ * `<style type="text/css">` tag with the content.
784
+ * @returns Promise which resolves to the added tag when the stylesheet's
785
+ * onload fires or when the CSS content was injected into frame.
786
+ */
787
+ async addStyleTag(options) {
788
+ return this.mainFrame().addStyleTag(options);
789
+ }
790
+ /**
791
+ * The method adds a function called `name` on the page's `window` object. When
792
+ * called, the function executes `puppeteerFunction` in node.js and returns a
793
+ * `Promise` which resolves to the return value of `puppeteerFunction`.
794
+ *
795
+ * If the puppeteerFunction returns a `Promise`, it will be awaited.
796
+ *
797
+ * NOTE: Functions installed via `page.exposeFunction` survive navigations.
798
+ * @param name - Name of the function on the window object
799
+ * @param puppeteerFunction - Callback function which will be called in
800
+ * Puppeteer's context.
801
+ * @example
802
+ * An example of adding an `md5` function into the page:
803
+ * ```js
804
+ * const puppeteer = require('puppeteer');
805
+ * const crypto = require('crypto');
806
+ *
807
+ * (async () => {
808
+ * const browser = await puppeteer.launch();
809
+ * const page = await browser.newPage();
810
+ * page.on('console', (msg) => console.log(msg.text()));
811
+ * await page.exposeFunction('md5', (text) =>
812
+ * crypto.createHash('md5').update(text).digest('hex')
813
+ * );
814
+ * await page.evaluate(async () => {
815
+ * // use window.md5 to compute hashes
816
+ * const myString = 'PUPPETEER';
817
+ * const myHash = await window.md5(myString);
818
+ * console.log(`md5 of ${myString} is ${myHash}`);
819
+ * });
820
+ * await browser.close();
821
+ * })();
822
+ * ```
823
+ * An example of adding a `window.readfile` function into the page:
824
+ * ```js
825
+ * const puppeteer = require('puppeteer');
826
+ * const fs = require('fs');
827
+ *
828
+ * (async () => {
829
+ * const browser = await puppeteer.launch();
830
+ * const page = await browser.newPage();
831
+ * page.on('console', (msg) => console.log(msg.text()));
832
+ * await page.exposeFunction('readfile', async (filePath) => {
833
+ * return new Promise((resolve, reject) => {
834
+ * fs.readFile(filePath, 'utf8', (err, text) => {
835
+ * if (err) reject(err);
836
+ * else resolve(text);
837
+ * });
838
+ * });
839
+ * });
840
+ * await page.evaluate(async () => {
841
+ * // use window.readfile to read contents of a file
842
+ * const content = await window.readfile('/etc/hosts');
843
+ * console.log(content);
844
+ * });
845
+ * await browser.close();
846
+ * })();
847
+ * ```
848
+ */
849
+ async exposeFunction(name, puppeteerFunction) {
850
+ if (this._pageBindings.has(name))
851
+ throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);
852
+ let exposedFunction;
853
+ if (typeof puppeteerFunction === 'function') {
854
+ exposedFunction = puppeteerFunction;
855
+ }
856
+ else if (typeof puppeteerFunction.default === 'function') {
857
+ exposedFunction = puppeteerFunction.default;
858
+ }
859
+ else {
860
+ throw new Error(`Failed to add page binding with name ${name}: ${puppeteerFunction} is not a function or a module with a default export.`);
861
+ }
862
+ this._pageBindings.set(name, exposedFunction);
863
+ const expression = helper.pageBindingInitString('exposedFun', name);
864
+ await this._client.send('Runtime.addBinding', { name: name });
865
+ await this._client.send('Page.addScriptToEvaluateOnNewDocument', {
866
+ source: expression,
867
+ });
868
+ await Promise.all(this.frames().map((frame) => frame.evaluate(expression).catch(debugError)));
869
+ }
870
+ /**
871
+ * Provide credentials for `HTTP authentication`.
872
+ * @remarks To disable authentication, pass `null`.
873
+ */
874
+ async authenticate(credentials) {
875
+ return this._frameManager.networkManager().authenticate(credentials);
876
+ }
877
+ /**
878
+ * The extra HTTP headers will be sent with every request the page initiates.
879
+ * NOTE: All HTTP header names are lowercased. (HTTP headers are
880
+ * case-insensitive, so this shouldn’t impact your server code.)
881
+ * NOTE: page.setExtraHTTPHeaders does not guarantee the order of headers in
882
+ * the outgoing requests.
883
+ * @param headers - An object containing additional HTTP headers to be sent
884
+ * with every request. All header values must be strings.
885
+ * @returns
886
+ */
887
+ async setExtraHTTPHeaders(headers) {
888
+ return this._frameManager.networkManager().setExtraHTTPHeaders(headers);
889
+ }
890
+ /**
891
+ * @param userAgent - Specific user agent to use in this page
892
+ * @param userAgentData - Specific user agent client hint data to use in this
893
+ * page
894
+ * @returns Promise which resolves when the user agent is set.
895
+ */
896
+ async setUserAgent(userAgent, userAgentMetadata) {
897
+ return this._frameManager
898
+ .networkManager()
899
+ .setUserAgent(userAgent, userAgentMetadata);
900
+ }
901
+ /**
902
+ * @returns Object containing metrics as key/value pairs.
903
+ *
904
+ * - `Timestamp` : The timestamp when the metrics sample was taken.
905
+ *
906
+ * - `Documents` : Number of documents in the page.
907
+ *
908
+ * - `Frames` : Number of frames in the page.
909
+ *
910
+ * - `JSEventListeners` : Number of events in the page.
911
+ *
912
+ * - `Nodes` : Number of DOM nodes in the page.
913
+ *
914
+ * - `LayoutCount` : Total number of full or partial page layout.
915
+ *
916
+ * - `RecalcStyleCount` : Total number of page style recalculations.
917
+ *
918
+ * - `LayoutDuration` : Combined durations of all page layouts.
919
+ *
920
+ * - `RecalcStyleDuration` : Combined duration of all page style
921
+ * recalculations.
922
+ *
923
+ * - `ScriptDuration` : Combined duration of JavaScript execution.
924
+ *
925
+ * - `TaskDuration` : Combined duration of all tasks performed by the browser.
926
+ *
927
+ *
928
+ * - `JSHeapUsedSize` : Used JavaScript heap size.
929
+ *
930
+ * - `JSHeapTotalSize` : Total JavaScript heap size.
931
+ * @remarks
932
+ * NOTE: All timestamps are in monotonic time: monotonically increasing time
933
+ * in seconds since an arbitrary point in the past.
934
+ */
935
+ async metrics() {
936
+ const response = await this._client.send('Performance.getMetrics');
937
+ return this._buildMetricsObject(response.metrics);
938
+ }
939
+ _emitMetrics(event) {
940
+ this.emit("metrics" /* Metrics */, {
941
+ title: event.title,
942
+ metrics: this._buildMetricsObject(event.metrics),
943
+ });
944
+ }
945
+ _buildMetricsObject(metrics) {
946
+ const result = {};
947
+ for (const metric of metrics || []) {
948
+ if (supportedMetrics.has(metric.name))
949
+ result[metric.name] = metric.value;
950
+ }
951
+ return result;
952
+ }
953
+ _handleException(exceptionDetails) {
954
+ const message = helper.getExceptionMessage(exceptionDetails);
955
+ const err = new Error(message);
956
+ err.stack = ''; // Don't report clientside error with a node stack attached
957
+ this.emit("pageerror" /* PageError */, err);
958
+ }
959
+ async _onConsoleAPI(event) {
960
+ if (event.executionContextId === 0) {
961
+ // DevTools protocol stores the last 1000 console messages. These
962
+ // messages are always reported even for removed execution contexts. In
963
+ // this case, they are marked with executionContextId = 0 and are
964
+ // reported upon enabling Runtime agent.
965
+ //
966
+ // Ignore these messages since:
967
+ // - there's no execution context we can use to operate with message
968
+ // arguments
969
+ // - these messages are reported before Puppeteer clients can subscribe
970
+ // to the 'console'
971
+ // page event.
972
+ //
973
+ // @see https://github.com/puppeteer/puppeteer/issues/3865
974
+ return;
975
+ }
976
+ const context = this._frameManager.executionContextById(event.executionContextId, this._client);
977
+ const values = event.args.map((arg) => createJSHandle(context, arg));
978
+ this._addConsoleMessage(event.type, values, event.stackTrace);
979
+ }
980
+ async _onBindingCalled(event) {
981
+ let payload;
982
+ try {
983
+ payload = JSON.parse(event.payload);
984
+ }
985
+ catch {
986
+ // The binding was either called by something in the page or it was
987
+ // called before our wrapper was initialized.
988
+ return;
989
+ }
990
+ const { type, name, seq, args } = payload;
991
+ if (type !== 'exposedFun' || !this._pageBindings.has(name))
992
+ return;
993
+ let expression = null;
994
+ try {
995
+ const result = await this._pageBindings.get(name)(...args);
996
+ expression = helper.pageBindingDeliverResultString(name, seq, result);
997
+ }
998
+ catch (error) {
999
+ if (error instanceof Error)
1000
+ expression = helper.pageBindingDeliverErrorString(name, seq, error.message, error.stack);
1001
+ else
1002
+ expression = helper.pageBindingDeliverErrorValueString(name, seq, error);
1003
+ }
1004
+ this._client
1005
+ .send('Runtime.evaluate', {
1006
+ expression,
1007
+ contextId: event.executionContextId,
1008
+ })
1009
+ .catch(debugError);
1010
+ }
1011
+ _addConsoleMessage(type, args, stackTrace) {
1012
+ if (!this.listenerCount("console" /* Console */)) {
1013
+ args.forEach((arg) => arg.dispose());
1014
+ return;
1015
+ }
1016
+ const textTokens = [];
1017
+ for (const arg of args) {
1018
+ const remoteObject = arg._remoteObject;
1019
+ if (remoteObject.objectId)
1020
+ textTokens.push(arg.toString());
1021
+ else
1022
+ textTokens.push(helper.valueFromRemoteObject(remoteObject));
1023
+ }
1024
+ const stackTraceLocations = [];
1025
+ if (stackTrace) {
1026
+ for (const callFrame of stackTrace.callFrames) {
1027
+ stackTraceLocations.push({
1028
+ url: callFrame.url,
1029
+ lineNumber: callFrame.lineNumber,
1030
+ columnNumber: callFrame.columnNumber,
1031
+ });
1032
+ }
1033
+ }
1034
+ const message = new ConsoleMessage(type, textTokens.join(' '), args, stackTraceLocations);
1035
+ this.emit("console" /* Console */, message);
1036
+ }
1037
+ _onDialog(event) {
1038
+ let dialogType = null;
1039
+ const validDialogTypes = new Set([
1040
+ 'alert',
1041
+ 'confirm',
1042
+ 'prompt',
1043
+ 'beforeunload',
1044
+ ]);
1045
+ if (validDialogTypes.has(event.type)) {
1046
+ dialogType = event.type;
1047
+ }
1048
+ assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
1049
+ const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt);
1050
+ this.emit("dialog" /* Dialog */, dialog);
1051
+ }
1052
+ /**
1053
+ * Resets default white background
1054
+ */
1055
+ async _resetDefaultBackgroundColor() {
1056
+ await this._client.send('Emulation.setDefaultBackgroundColorOverride');
1057
+ }
1058
+ /**
1059
+ * Hides default white background
1060
+ */
1061
+ async _setTransparentBackgroundColor() {
1062
+ await this._client.send('Emulation.setDefaultBackgroundColorOverride', {
1063
+ color: { r: 0, g: 0, b: 0, a: 0 },
1064
+ });
1065
+ }
1066
+ /**
1067
+ *
1068
+ * @returns
1069
+ * @remarks Shortcut for
1070
+ * {@link Frame.url | page.mainFrame().url()}.
1071
+ */
1072
+ url() {
1073
+ return this.mainFrame().url();
1074
+ }
1075
+ async content() {
1076
+ return await this._frameManager.mainFrame().content();
1077
+ }
1078
+ /**
1079
+ * @param html - HTML markup to assign to the page.
1080
+ * @param options - Parameters that has some properties.
1081
+ * @remarks
1082
+ * The parameter `options` might have the following options.
1083
+ *
1084
+ * - `timeout` : Maximum time in milliseconds for resources to load, defaults
1085
+ * to 30 seconds, pass `0` to disable timeout. The default value can be
1086
+ * changed by using the
1087
+ * {@link Page.setDefaultNavigationTimeout |
1088
+ * page.setDefaultNavigationTimeout(timeout)}
1089
+ * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1090
+ * methods.
1091
+ *
1092
+ * - `waitUntil`: When to consider setting markup succeeded, defaults to `load`.
1093
+ * Given an array of event strings, setting content is considered to be
1094
+ * successful after all events have been fired. Events can be either:<br/>
1095
+ * - `load` : consider setting content to be finished when the `load` event is
1096
+ * fired.<br/>
1097
+ * - `domcontentloaded` : consider setting content to be finished when the
1098
+ * `DOMContentLoaded` event is fired.<br/>
1099
+ * - `networkidle0` : consider setting content to be finished when there are no
1100
+ * more than 0 network connections for at least `500` ms.<br/>
1101
+ * - `networkidle2` : consider setting content to be finished when there are no
1102
+ * more than 2 network connections for at least `500` ms.
1103
+ */
1104
+ async setContent(html, options = {}) {
1105
+ await this._frameManager.mainFrame().setContent(html, options);
1106
+ }
1107
+ /**
1108
+ * @param url - URL to navigate page to. The URL should include scheme, e.g.
1109
+ * `https://`
1110
+ * @param options - Navigation Parameter
1111
+ * @returns Promise which resolves to the main resource response. In case of
1112
+ * multiple redirects, the navigation will resolve with the response of the
1113
+ * last redirect.
1114
+ * @remarks
1115
+ * The argument `options` might have the following properties:
1116
+ *
1117
+ * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
1118
+ * seconds, pass 0 to disable timeout. The default value can be changed by
1119
+ * using the
1120
+ * {@link Page.setDefaultNavigationTimeout |
1121
+ * page.setDefaultNavigationTimeout(timeout)}
1122
+ * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1123
+ * methods.
1124
+ *
1125
+ * - `waitUntil`:When to consider navigation succeeded, defaults to `load`.
1126
+ * Given an array of event strings, navigation is considered to be successful
1127
+ * after all events have been fired. Events can be either:<br/>
1128
+ * - `load` : consider navigation to be finished when the load event is
1129
+ * fired.<br/>
1130
+ * - `domcontentloaded` : consider navigation to be finished when the
1131
+ * DOMContentLoaded event is fired.<br/>
1132
+ * - `networkidle0` : consider navigation to be finished when there are no
1133
+ * more than 0 network connections for at least `500` ms.<br/>
1134
+ * - `networkidle2` : consider navigation to be finished when there are no
1135
+ * more than 2 network connections for at least `500` ms.
1136
+ *
1137
+ * - `referer` : Referer header value. If provided it will take preference
1138
+ * over the referer header value set by
1139
+ * {@link Page.setExtraHTTPHeaders |page.setExtraHTTPHeaders()}.
1140
+ *
1141
+ * `page.goto` will throw an error if:
1142
+ * - there's an SSL error (e.g. in case of self-signed certificates).
1143
+ * - target URL is invalid.
1144
+ * - the timeout is exceeded during navigation.
1145
+ * - the remote server does not respond or is unreachable.
1146
+ * - the main resource failed to load.
1147
+ *
1148
+ * `page.goto` will not throw an error when any valid HTTP status code is
1149
+ * returned by the remote server, including 404 "Not Found" and 500
1150
+ * "Internal Server Error". The status code for such responses can be
1151
+ * retrieved by calling response.status().
1152
+ *
1153
+ * NOTE: `page.goto` either throws an error or returns a main resource
1154
+ * response. The only exceptions are navigation to about:blank or navigation
1155
+ * to the same URL with a different hash, which would succeed and return null.
1156
+ *
1157
+ * NOTE: Headless mode doesn't support navigation to a PDF document. See the
1158
+ * {@link https://bugs.chromium.org/p/chromium/issues/detail?id=761295
1159
+ * | upstream issue}.
1160
+ *
1161
+ * Shortcut for {@link Frame.goto | page.mainFrame().goto(url, options)}.
1162
+ */
1163
+ async goto(url, options = {}) {
1164
+ return await this._frameManager.mainFrame().goto(url, options);
1165
+ }
1166
+ /**
1167
+ * @param options - Navigation parameters which might have the following
1168
+ * properties:
1169
+ * @returns Promise which resolves to the main resource response. In case of
1170
+ * multiple redirects, the navigation will resolve with the response of the
1171
+ * last redirect.
1172
+ * @remarks
1173
+ * The argument `options` might have the following properties:
1174
+ *
1175
+ * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
1176
+ * seconds, pass 0 to disable timeout. The default value can be changed by
1177
+ * using the
1178
+ * {@link Page.setDefaultNavigationTimeout |
1179
+ * page.setDefaultNavigationTimeout(timeout)}
1180
+ * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1181
+ * methods.
1182
+ *
1183
+ * - `waitUntil`: When to consider navigation succeeded, defaults to `load`.
1184
+ * Given an array of event strings, navigation is considered to be
1185
+ * successful after all events have been fired. Events can be either:<br/>
1186
+ * - `load` : consider navigation to be finished when the load event is fired.<br/>
1187
+ * - `domcontentloaded` : consider navigation to be finished when the
1188
+ * DOMContentLoaded event is fired.<br/>
1189
+ * - `networkidle0` : consider navigation to be finished when there are no
1190
+ * more than 0 network connections for at least `500` ms.<br/>
1191
+ * - `networkidle2` : consider navigation to be finished when there are no
1192
+ * more than 2 network connections for at least `500` ms.
1193
+ */
1194
+ async reload(options) {
1195
+ const result = await Promise.all([
1196
+ this.waitForNavigation(options),
1197
+ this._client.send('Page.reload'),
1198
+ ]);
1199
+ return result[0];
1200
+ }
1201
+ /**
1202
+ * This resolves when the page navigates to a new URL or reloads. It is useful
1203
+ * when you run code that will indirectly cause the page to navigate. Consider
1204
+ * this example:
1205
+ * ```js
1206
+ * const [response] = await Promise.all([
1207
+ * page.waitForNavigation(), // The promise resolves after navigation has finished
1208
+ * page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
1209
+ * ]);
1210
+ * ```
1211
+ *
1212
+ * @param options - Navigation parameters which might have the following properties:
1213
+ * @returns Promise which resolves to the main resource response. In case of
1214
+ * multiple redirects, the navigation will resolve with the response of the
1215
+ * last redirect. In case of navigation to a different anchor or navigation
1216
+ * due to History API usage, the navigation will resolve with `null`.
1217
+ * @remarks
1218
+ * NOTE: Usage of the
1219
+ * {@link https://developer.mozilla.org/en-US/docs/Web/API/History_API | History API}
1220
+ * to change the URL is considered a navigation.
1221
+ *
1222
+ * Shortcut for
1223
+ * {@link Frame.waitForNavigation | page.mainFrame().waitForNavigation(options)}.
1224
+ */
1225
+ async waitForNavigation(options = {}) {
1226
+ return await this._frameManager.mainFrame().waitForNavigation(options);
1227
+ }
1228
+ _sessionClosePromise() {
1229
+ if (!this._disconnectPromise)
1230
+ this._disconnectPromise = new Promise((fulfill) => this._client.once(CDPSessionEmittedEvents.Disconnected, () => fulfill(new Error('Target closed'))));
1231
+ return this._disconnectPromise;
1232
+ }
1233
+ /**
1234
+ * @param urlOrPredicate - A URL or predicate to wait for
1235
+ * @param options - Optional waiting parameters
1236
+ * @returns Promise which resolves to the matched response
1237
+ * @example
1238
+ * ```js
1239
+ * const firstResponse = await page.waitForResponse(
1240
+ * 'https://example.com/resource'
1241
+ * );
1242
+ * const finalResponse = await page.waitForResponse(
1243
+ * (response) =>
1244
+ * response.url() === 'https://example.com' && response.status() === 200
1245
+ * );
1246
+ * const finalResponse = await page.waitForResponse(async (response) => {
1247
+ * return (await response.text()).includes('<html>');
1248
+ * });
1249
+ * return finalResponse.ok();
1250
+ * ```
1251
+ * @remarks
1252
+ * Optional Waiting Parameters have:
1253
+ *
1254
+ * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds, pass
1255
+ * `0` to disable the timeout. The default value can be changed by using the
1256
+ * {@link Page.setDefaultTimeout} method.
1257
+ */
1258
+ async waitForRequest(urlOrPredicate, options = {}) {
1259
+ const { timeout = this._timeoutSettings.timeout() } = options;
1260
+ return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEmittedEvents.Request, (request) => {
1261
+ if (helper.isString(urlOrPredicate))
1262
+ return urlOrPredicate === request.url();
1263
+ if (typeof urlOrPredicate === 'function')
1264
+ return !!urlOrPredicate(request);
1265
+ return false;
1266
+ }, timeout, this._sessionClosePromise());
1267
+ }
1268
+ /**
1269
+ * @param urlOrPredicate - A URL or predicate to wait for.
1270
+ * @param options - Optional waiting parameters
1271
+ * @returns Promise which resolves to the matched response.
1272
+ * @example
1273
+ * ```js
1274
+ * const firstResponse = await page.waitForResponse(
1275
+ * 'https://example.com/resource'
1276
+ * );
1277
+ * const finalResponse = await page.waitForResponse(
1278
+ * (response) =>
1279
+ * response.url() === 'https://example.com' && response.status() === 200
1280
+ * );
1281
+ * const finalResponse = await page.waitForResponse(async (response) => {
1282
+ * return (await response.text()).includes('<html>');
1283
+ * });
1284
+ * return finalResponse.ok();
1285
+ * ```
1286
+ * @remarks
1287
+ * Optional Parameter have:
1288
+ *
1289
+ * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds,
1290
+ * pass `0` to disable the timeout. The default value can be changed by using
1291
+ * the {@link Page.setDefaultTimeout} method.
1292
+ */
1293
+ async waitForResponse(urlOrPredicate, options = {}) {
1294
+ const { timeout = this._timeoutSettings.timeout() } = options;
1295
+ return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEmittedEvents.Response, async (response) => {
1296
+ if (helper.isString(urlOrPredicate))
1297
+ return urlOrPredicate === response.url();
1298
+ if (typeof urlOrPredicate === 'function')
1299
+ return !!(await urlOrPredicate(response));
1300
+ return false;
1301
+ }, timeout, this._sessionClosePromise());
1302
+ }
1303
+ /**
1304
+ * @param options - Optional waiting parameters
1305
+ * @returns Promise which resolves when network is idle
1306
+ */
1307
+ async waitForNetworkIdle(options = {}) {
1308
+ const { idleTime = 500, timeout = this._timeoutSettings.timeout() } = options;
1309
+ const networkManager = this._frameManager.networkManager();
1310
+ let idleResolveCallback;
1311
+ const idlePromise = new Promise((resolve) => {
1312
+ idleResolveCallback = resolve;
1313
+ });
1314
+ let abortRejectCallback;
1315
+ const abortPromise = new Promise((_, reject) => {
1316
+ abortRejectCallback = reject;
1317
+ });
1318
+ let idleTimer;
1319
+ const onIdle = () => idleResolveCallback();
1320
+ const cleanup = () => {
1321
+ idleTimer && clearTimeout(idleTimer);
1322
+ abortRejectCallback(new Error('abort'));
1323
+ };
1324
+ const evaluate = () => {
1325
+ idleTimer && clearTimeout(idleTimer);
1326
+ if (networkManager.numRequestsInProgress() === 0)
1327
+ idleTimer = setTimeout(onIdle, idleTime);
1328
+ };
1329
+ evaluate();
1330
+ const eventHandler = () => {
1331
+ evaluate();
1332
+ return false;
1333
+ };
1334
+ const listenToEvent = (event) => helper.waitForEvent(networkManager, event, eventHandler, timeout, abortPromise);
1335
+ const eventPromises = [
1336
+ listenToEvent(NetworkManagerEmittedEvents.Request),
1337
+ listenToEvent(NetworkManagerEmittedEvents.Response),
1338
+ ];
1339
+ await Promise.race([
1340
+ idlePromise,
1341
+ ...eventPromises,
1342
+ this._sessionClosePromise(),
1343
+ ]).then((r) => {
1344
+ cleanup();
1345
+ return r;
1346
+ }, (error) => {
1347
+ cleanup();
1348
+ throw error;
1349
+ });
1350
+ }
1351
+ /**
1352
+ * @param urlOrPredicate - A URL or predicate to wait for.
1353
+ * @param options - Optional waiting parameters
1354
+ * @returns Promise which resolves to the matched frame.
1355
+ * @example
1356
+ * ```js
1357
+ * const frame = await page.waitForFrame(async (frame) => {
1358
+ * return frame.name() === 'Test';
1359
+ * });
1360
+ * ```
1361
+ * @remarks
1362
+ * Optional Parameter have:
1363
+ *
1364
+ * - `timeout`: Maximum wait time in milliseconds, defaults to `30` seconds,
1365
+ * pass `0` to disable the timeout. The default value can be changed by using
1366
+ * the {@link Page.setDefaultTimeout} method.
1367
+ */
1368
+ async waitForFrame(urlOrPredicate, options = {}) {
1369
+ const { timeout = this._timeoutSettings.timeout() } = options;
1370
+ async function predicate(frame) {
1371
+ if (helper.isString(urlOrPredicate))
1372
+ return urlOrPredicate === frame.url();
1373
+ if (typeof urlOrPredicate === 'function')
1374
+ return !!(await urlOrPredicate(frame));
1375
+ return false;
1376
+ }
1377
+ return Promise.race([
1378
+ helper.waitForEvent(this._frameManager, FrameManagerEmittedEvents.FrameAttached, predicate, timeout, this._sessionClosePromise()),
1379
+ helper.waitForEvent(this._frameManager, FrameManagerEmittedEvents.FrameNavigated, predicate, timeout, this._sessionClosePromise()),
1380
+ ]);
1381
+ }
1382
+ /**
1383
+ * This method navigate to the previous page in history.
1384
+ * @param options - Navigation parameters
1385
+ * @returns Promise which resolves to the main resource response. In case of
1386
+ * multiple redirects, the navigation will resolve with the response of the
1387
+ * last redirect. If can not go back, resolves to `null`.
1388
+ * @remarks
1389
+ * The argument `options` might have the following properties:
1390
+ *
1391
+ * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
1392
+ * seconds, pass 0 to disable timeout. The default value can be changed by
1393
+ * using the
1394
+ * {@link Page.setDefaultNavigationTimeout
1395
+ * | page.setDefaultNavigationTimeout(timeout)}
1396
+ * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1397
+ * methods.
1398
+ *
1399
+ * - `waitUntil` : When to consider navigation succeeded, defaults to `load`.
1400
+ * Given an array of event strings, navigation is considered to be
1401
+ * successful after all events have been fired. Events can be either:<br/>
1402
+ * - `load` : consider navigation to be finished when the load event is fired.<br/>
1403
+ * - `domcontentloaded` : consider navigation to be finished when the
1404
+ * DOMContentLoaded event is fired.<br/>
1405
+ * - `networkidle0` : consider navigation to be finished when there are no
1406
+ * more than 0 network connections for at least `500` ms.<br/>
1407
+ * - `networkidle2` : consider navigation to be finished when there are no
1408
+ * more than 2 network connections for at least `500` ms.
1409
+ */
1410
+ async goBack(options = {}) {
1411
+ return this._go(-1, options);
1412
+ }
1413
+ /**
1414
+ * This method navigate to the next page in history.
1415
+ * @param options - Navigation Parameter
1416
+ * @returns Promise which resolves to the main resource response. In case of
1417
+ * multiple redirects, the navigation will resolve with the response of the
1418
+ * last redirect. If can not go forward, resolves to `null`.
1419
+ * @remarks
1420
+ * The argument `options` might have the following properties:
1421
+ *
1422
+ * - `timeout` : Maximum navigation time in milliseconds, defaults to 30
1423
+ * seconds, pass 0 to disable timeout. The default value can be changed by
1424
+ * using the
1425
+ * {@link Page.setDefaultNavigationTimeout
1426
+ * | page.setDefaultNavigationTimeout(timeout)}
1427
+ * or {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)}
1428
+ * methods.
1429
+ *
1430
+ * - `waitUntil`: When to consider navigation succeeded, defaults to `load`.
1431
+ * Given an array of event strings, navigation is considered to be
1432
+ * successful after all events have been fired. Events can be either:<br/>
1433
+ * - `load` : consider navigation to be finished when the load event is fired.<br/>
1434
+ * - `domcontentloaded` : consider navigation to be finished when the
1435
+ * DOMContentLoaded event is fired.<br/>
1436
+ * - `networkidle0` : consider navigation to be finished when there are no
1437
+ * more than 0 network connections for at least `500` ms.<br/>
1438
+ * - `networkidle2` : consider navigation to be finished when there are no
1439
+ * more than 2 network connections for at least `500` ms.
1440
+ */
1441
+ async goForward(options = {}) {
1442
+ return this._go(+1, options);
1443
+ }
1444
+ async _go(delta, options) {
1445
+ const history = await this._client.send('Page.getNavigationHistory');
1446
+ const entry = history.entries[history.currentIndex + delta];
1447
+ if (!entry)
1448
+ return null;
1449
+ const result = await Promise.all([
1450
+ this.waitForNavigation(options),
1451
+ this._client.send('Page.navigateToHistoryEntry', { entryId: entry.id }),
1452
+ ]);
1453
+ return result[0];
1454
+ }
1455
+ /**
1456
+ * Brings page to front (activates tab).
1457
+ */
1458
+ async bringToFront() {
1459
+ await this._client.send('Page.bringToFront');
1460
+ }
1461
+ /**
1462
+ * Emulates given device metrics and user agent. This method is a shortcut for
1463
+ * calling two methods: {@link Page.setUserAgent} and {@link Page.setViewport}
1464
+ * To aid emulation, Puppeteer provides a list of device descriptors that can
1465
+ * be obtained via the {@link Puppeteer.devices} `page.emulate` will resize
1466
+ * the page. A lot of websites don't expect phones to change size, so you
1467
+ * should emulate before navigating to the page.
1468
+ * @example
1469
+ * ```js
1470
+ * const puppeteer = require('puppeteer');
1471
+ * const iPhone = puppeteer.devices['iPhone 6'];
1472
+ * (async () => {
1473
+ * const browser = await puppeteer.launch();
1474
+ * const page = await browser.newPage();
1475
+ * await page.emulate(iPhone);
1476
+ * await page.goto('https://www.google.com');
1477
+ * // other actions...
1478
+ * await browser.close();
1479
+ * })();
1480
+ * ```
1481
+ * @remarks List of all available devices is available in the source code:
1482
+ * {@link https://github.com/puppeteer/puppeteer/blob/main/src/common/DeviceDescriptors.ts | src/common/DeviceDescriptors.ts}.
1483
+ */
1484
+ async emulate(options) {
1485
+ await Promise.all([
1486
+ this.setViewport(options.viewport),
1487
+ this.setUserAgent(options.userAgent),
1488
+ ]);
1489
+ }
1490
+ /**
1491
+ * @param enabled - Whether or not to enable JavaScript on the page.
1492
+ * @returns
1493
+ * @remarks
1494
+ * NOTE: changing this value won't affect scripts that have already been run.
1495
+ * It will take full effect on the next navigation.
1496
+ */
1497
+ async setJavaScriptEnabled(enabled) {
1498
+ if (this._javascriptEnabled === enabled)
1499
+ return;
1500
+ this._javascriptEnabled = enabled;
1501
+ await this._client.send('Emulation.setScriptExecutionDisabled', {
1502
+ value: !enabled,
1503
+ });
1504
+ }
1505
+ /**
1506
+ * Toggles bypassing page's Content-Security-Policy.
1507
+ * @param enabled - sets bypassing of page's Content-Security-Policy.
1508
+ * @remarks
1509
+ * NOTE: CSP bypassing happens at the moment of CSP initialization rather than
1510
+ * evaluation. Usually, this means that `page.setBypassCSP` should be called
1511
+ * before navigating to the domain.
1512
+ */
1513
+ async setBypassCSP(enabled) {
1514
+ await this._client.send('Page.setBypassCSP', { enabled });
1515
+ }
1516
+ /**
1517
+ * @param type - Changes the CSS media type of the page. The only allowed
1518
+ * values are `screen`, `print` and `null`. Passing `null` disables CSS media
1519
+ * emulation.
1520
+ * @example
1521
+ * ```
1522
+ * await page.evaluate(() => matchMedia('screen').matches);
1523
+ * // true
1524
+ * await page.evaluate(() => matchMedia('print').matches);
1525
+ * // false
1526
+ *
1527
+ * await page.emulateMediaType('print');
1528
+ * await page.evaluate(() => matchMedia('screen').matches);
1529
+ * // → false
1530
+ * await page.evaluate(() => matchMedia('print').matches);
1531
+ * // → true
1532
+ *
1533
+ * await page.emulateMediaType(null);
1534
+ * await page.evaluate(() => matchMedia('screen').matches);
1535
+ * // true
1536
+ * await page.evaluate(() => matchMedia('print').matches);
1537
+ * // → false
1538
+ * ```
1539
+ */
1540
+ async emulateMediaType(type) {
1541
+ assert(type === 'screen' || type === 'print' || type === null, 'Unsupported media type: ' + type);
1542
+ await this._client.send('Emulation.setEmulatedMedia', {
1543
+ media: type || '',
1544
+ });
1545
+ }
1546
+ /**
1547
+ * Enables CPU throttling to emulate slow CPUs.
1548
+ * @param factor - slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).
1549
+ */
1550
+ async emulateCPUThrottling(factor) {
1551
+ assert(factor === null || factor >= 1, 'Throttling rate should be greater or equal to 1');
1552
+ await this._client.send('Emulation.setCPUThrottlingRate', {
1553
+ rate: factor !== null ? factor : 1,
1554
+ });
1555
+ }
1556
+ /**
1557
+ * @param features - `<?Array<Object>>` Given an array of media feature
1558
+ * objects, emulates CSS media features on the page. Each media feature object
1559
+ * must have the following properties:
1560
+ * @example
1561
+ * ```js
1562
+ * await page.emulateMediaFeatures([
1563
+ * { name: 'prefers-color-scheme', value: 'dark' },
1564
+ * ]);
1565
+ * await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
1566
+ * // → true
1567
+ * await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
1568
+ * // → false
1569
+ *
1570
+ * await page.emulateMediaFeatures([
1571
+ * { name: 'prefers-reduced-motion', value: 'reduce' },
1572
+ * ]);
1573
+ * await page.evaluate(
1574
+ * () => matchMedia('(prefers-reduced-motion: reduce)').matches
1575
+ * );
1576
+ * // true
1577
+ * await page.evaluate(
1578
+ * () => matchMedia('(prefers-reduced-motion: no-preference)').matches
1579
+ * );
1580
+ * // → false
1581
+ *
1582
+ * await page.emulateMediaFeatures([
1583
+ * { name: 'prefers-color-scheme', value: 'dark' },
1584
+ * { name: 'prefers-reduced-motion', value: 'reduce' },
1585
+ * ]);
1586
+ * await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
1587
+ * // true
1588
+ * await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
1589
+ * // → false
1590
+ * await page.evaluate(
1591
+ * () => matchMedia('(prefers-reduced-motion: reduce)').matches
1592
+ * );
1593
+ * // true
1594
+ * await page.evaluate(
1595
+ * () => matchMedia('(prefers-reduced-motion: no-preference)').matches
1596
+ * );
1597
+ * // → false
1598
+ *
1599
+ * await page.emulateMediaFeatures([{ name: 'color-gamut', value: 'p3' }]);
1600
+ * await page.evaluate(() => matchMedia('(color-gamut: srgb)').matches);
1601
+ * // → true
1602
+ * await page.evaluate(() => matchMedia('(color-gamut: p3)').matches);
1603
+ * // → true
1604
+ * await page.evaluate(() => matchMedia('(color-gamut: rec2020)').matches);
1605
+ * // false
1606
+ * ```
1607
+ */
1608
+ async emulateMediaFeatures(features) {
1609
+ if (features === null)
1610
+ await this._client.send('Emulation.setEmulatedMedia', { features: null });
1611
+ if (Array.isArray(features)) {
1612
+ features.every((mediaFeature) => {
1613
+ const name = mediaFeature.name;
1614
+ assert(/^(?:prefers-(?:color-scheme|reduced-motion)|color-gamut)$/.test(name), 'Unsupported media feature: ' + name);
1615
+ return true;
1616
+ });
1617
+ await this._client.send('Emulation.setEmulatedMedia', {
1618
+ features: features,
1619
+ });
1620
+ }
1621
+ }
1622
+ /**
1623
+ * @param timezoneId - Changes the timezone of the page. See
1624
+ * {@link https://source.chromium.org/chromium/chromium/deps/icu.git/+/faee8bc70570192d82d2978a71e2a615788597d1:source/data/misc/metaZones.txt | ICU’s metaZones.txt}
1625
+ * for a list of supported timezone IDs. Passing
1626
+ * `null` disables timezone emulation.
1627
+ */
1628
+ async emulateTimezone(timezoneId) {
1629
+ try {
1630
+ await this._client.send('Emulation.setTimezoneOverride', {
1631
+ timezoneId: timezoneId || '',
1632
+ });
1633
+ }
1634
+ catch (error) {
1635
+ if (error.message.includes('Invalid timezone'))
1636
+ throw new Error(`Invalid timezone ID: ${timezoneId}`);
1637
+ throw error;
1638
+ }
1639
+ }
1640
+ /**
1641
+ * Emulates the idle state.
1642
+ * If no arguments set, clears idle state emulation.
1643
+ *
1644
+ * @example
1645
+ * ```js
1646
+ * // set idle emulation
1647
+ * await page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});
1648
+ *
1649
+ * // do some checks here
1650
+ * ...
1651
+ *
1652
+ * // clear idle emulation
1653
+ * await page.emulateIdleState();
1654
+ * ```
1655
+ *
1656
+ * @param overrides - Mock idle state. If not set, clears idle overrides
1657
+ */
1658
+ async emulateIdleState(overrides) {
1659
+ if (overrides) {
1660
+ await this._client.send('Emulation.setIdleOverride', {
1661
+ isUserActive: overrides.isUserActive,
1662
+ isScreenUnlocked: overrides.isScreenUnlocked,
1663
+ });
1664
+ }
1665
+ else {
1666
+ await this._client.send('Emulation.clearIdleOverride');
1667
+ }
1668
+ }
1669
+ /**
1670
+ * Simulates the given vision deficiency on the page.
1671
+ *
1672
+ * @example
1673
+ * ```js
1674
+ * const puppeteer = require('puppeteer');
1675
+ *
1676
+ * (async () => {
1677
+ * const browser = await puppeteer.launch();
1678
+ * const page = await browser.newPage();
1679
+ * await page.goto('https://v8.dev/blog/10-years');
1680
+ *
1681
+ * await page.emulateVisionDeficiency('achromatopsia');
1682
+ * await page.screenshot({ path: 'achromatopsia.png' });
1683
+ *
1684
+ * await page.emulateVisionDeficiency('deuteranopia');
1685
+ * await page.screenshot({ path: 'deuteranopia.png' });
1686
+ *
1687
+ * await page.emulateVisionDeficiency('blurredVision');
1688
+ * await page.screenshot({ path: 'blurred-vision.png' });
1689
+ *
1690
+ * await browser.close();
1691
+ * })();
1692
+ * ```
1693
+ *
1694
+ * @param type - the type of deficiency to simulate, or `'none'` to reset.
1695
+ */
1696
+ async emulateVisionDeficiency(type) {
1697
+ const visionDeficiencies = new Set([
1698
+ 'none',
1699
+ 'achromatopsia',
1700
+ 'blurredVision',
1701
+ 'deuteranopia',
1702
+ 'protanopia',
1703
+ 'tritanopia',
1704
+ ]);
1705
+ try {
1706
+ assert(!type || visionDeficiencies.has(type), `Unsupported vision deficiency: ${type}`);
1707
+ await this._client.send('Emulation.setEmulatedVisionDeficiency', {
1708
+ type: type || 'none',
1709
+ });
1710
+ }
1711
+ catch (error) {
1712
+ throw error;
1713
+ }
1714
+ }
1715
+ /**
1716
+ * `page.setViewport` will resize the page. A lot of websites don't expect
1717
+ * phones to change size, so you should set the viewport before navigating to
1718
+ * the page.
1719
+ *
1720
+ * In the case of multiple pages in a single browser, each page can have its
1721
+ * own viewport size.
1722
+ * @example
1723
+ * ```js
1724
+ * const page = await browser.newPage();
1725
+ * await page.setViewport({
1726
+ * width: 640,
1727
+ * height: 480,
1728
+ * deviceScaleFactor: 1,
1729
+ * });
1730
+ * await page.goto('https://example.com');
1731
+ * ```
1732
+ *
1733
+ * @param viewport -
1734
+ * @remarks
1735
+ * Argument viewport have following properties:
1736
+ *
1737
+ * - `width`: page width in pixels. required
1738
+ *
1739
+ * - `height`: page height in pixels. required
1740
+ *
1741
+ * - `deviceScaleFactor`: Specify device scale factor (can be thought of as
1742
+ * DPR). Defaults to `1`.
1743
+ *
1744
+ * - `isMobile`: Whether the meta viewport tag is taken into account. Defaults
1745
+ * to `false`.
1746
+ *
1747
+ * - `hasTouch`: Specifies if viewport supports touch events. Defaults to `false`
1748
+ *
1749
+ * - `isLandScape`: Specifies if viewport is in landscape mode. Defaults to false.
1750
+ *
1751
+ * NOTE: in certain cases, setting viewport will reload the page in order to
1752
+ * set the isMobile or hasTouch properties.
1753
+ */
1754
+ async setViewport(viewport) {
1755
+ const needsReload = await this._emulationManager.emulateViewport(viewport);
1756
+ this._viewport = viewport;
1757
+ if (needsReload)
1758
+ await this.reload();
1759
+ }
1760
+ /**
1761
+ * @returns
1762
+ *
1763
+ * - `width`: page's width in pixels
1764
+ *
1765
+ * - `height`: page's height in pixels
1766
+ *
1767
+ * - `deviceScalarFactor`: Specify device scale factor (can be though of as
1768
+ * dpr). Defaults to `1`.
1769
+ *
1770
+ * - `isMobile`: Whether the meta viewport tag is taken into account. Defaults
1771
+ * to `false`.
1772
+ *
1773
+ * - `hasTouch`: Specifies if viewport supports touch events. Defaults to
1774
+ * `false`.
1775
+ *
1776
+ * - `isLandScape`: Specifies if viewport is in landscape mode. Defaults to
1777
+ * `false`.
1778
+ */
1779
+ viewport() {
1780
+ return this._viewport;
1781
+ }
1782
+ /**
1783
+ * @remarks
1784
+ *
1785
+ * Evaluates a function in the page's context and returns the result.
1786
+ *
1787
+ * If the function passed to `page.evaluteHandle` returns a Promise, the
1788
+ * function will wait for the promise to resolve and return its value.
1789
+ *
1790
+ * @example
1791
+ *
1792
+ * ```js
1793
+ * const result = await frame.evaluate(() => {
1794
+ * return Promise.resolve(8 * 7);
1795
+ * });
1796
+ * console.log(result); // prints "56"
1797
+ * ```
1798
+ *
1799
+ * You can pass a string instead of a function (although functions are
1800
+ * recommended as they are easier to debug and use with TypeScript):
1801
+ *
1802
+ * @example
1803
+ * ```
1804
+ * const aHandle = await page.evaluate('1 + 2');
1805
+ * ```
1806
+ *
1807
+ * To get the best TypeScript experience, you should pass in as the
1808
+ * generic the type of `pageFunction`:
1809
+ *
1810
+ * ```
1811
+ * const aHandle = await page.evaluate<() => number>(() => 2);
1812
+ * ```
1813
+ *
1814
+ * @example
1815
+ *
1816
+ * {@link ElementHandle} instances (including {@link JSHandle}s) can be passed
1817
+ * as arguments to the `pageFunction`:
1818
+ *
1819
+ * ```
1820
+ * const bodyHandle = await page.$('body');
1821
+ * const html = await page.evaluate(body => body.innerHTML, bodyHandle);
1822
+ * await bodyHandle.dispose();
1823
+ * ```
1824
+ *
1825
+ * @param pageFunction - a function that is run within the page
1826
+ * @param args - arguments to be passed to the pageFunction
1827
+ *
1828
+ * @returns the return value of `pageFunction`.
1829
+ */
1830
+ async evaluate(pageFunction, ...args) {
1831
+ return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
1832
+ }
1833
+ /**
1834
+ * Adds a function which would be invoked in one of the following scenarios:
1835
+ *
1836
+ * - whenever the page is navigated
1837
+ *
1838
+ * - whenever the child frame is attached or navigated. In this case, the
1839
+ * function is invoked in the context of the newly attached frame.
1840
+ *
1841
+ * The function is invoked after the document was created but before any of
1842
+ * its scripts were run. This is useful to amend the JavaScript environment,
1843
+ * e.g. to seed `Math.random`.
1844
+ * @param pageFunction - Function to be evaluated in browser context
1845
+ * @param args - Arguments to pass to `pageFunction`
1846
+ * @example
1847
+ * An example of overriding the navigator.languages property before the page loads:
1848
+ * ```js
1849
+ * // preload.js
1850
+ *
1851
+ * // overwrite the `languages` property to use a custom getter
1852
+ * Object.defineProperty(navigator, 'languages', {
1853
+ * get: function () {
1854
+ * return ['en-US', 'en', 'bn'];
1855
+ * },
1856
+ * });
1857
+ *
1858
+ * // In your puppeteer script, assuming the preload.js file is
1859
+ * in same folder of our script
1860
+ * const preloadFile = fs.readFileSync('./preload.js', 'utf8');
1861
+ * await page.evaluateOnNewDocument(preloadFile);
1862
+ * ```
1863
+ */
1864
+ async evaluateOnNewDocument(pageFunction, ...args) {
1865
+ const source = helper.evaluationString(pageFunction, ...args);
1866
+ await this._client.send('Page.addScriptToEvaluateOnNewDocument', {
1867
+ source,
1868
+ });
1869
+ }
1870
+ /**
1871
+ * Toggles ignoring cache for each request based on the enabled state. By
1872
+ * default, caching is enabled.
1873
+ * @param enabled - sets the `enabled` state of cache
1874
+ */
1875
+ async setCacheEnabled(enabled = true) {
1876
+ await this._frameManager.networkManager().setCacheEnabled(enabled);
1877
+ }
1878
+ /**
1879
+ * @remarks
1880
+ * Options object which might have the following properties:
1881
+ *
1882
+ * - `path` : The file path to save the image to. The screenshot type
1883
+ * will be inferred from file extension. If `path` is a relative path, then
1884
+ * it is resolved relative to
1885
+ * {@link https://nodejs.org/api/process.html#process_process_cwd
1886
+ * | current working directory}.
1887
+ * If no path is provided, the image won't be saved to the disk.
1888
+ *
1889
+ * - `type` : Specify screenshot type, can be either `jpeg` or `png`.
1890
+ * Defaults to 'png'.
1891
+ *
1892
+ * - `quality` : The quality of the image, between 0-100. Not
1893
+ * applicable to `png` images.
1894
+ *
1895
+ * - `fullPage` : When true, takes a screenshot of the full
1896
+ * scrollable page. Defaults to `false`
1897
+ *
1898
+ * - `clip` : An object which specifies clipping region of the page.
1899
+ * Should have the following fields:<br/>
1900
+ * - `x` : x-coordinate of top-left corner of clip area.<br/>
1901
+ * - `y` : y-coordinate of top-left corner of clip area.<br/>
1902
+ * - `width` : width of clipping area.<br/>
1903
+ * - `height` : height of clipping area.
1904
+ *
1905
+ * - `omitBackground` : Hides default white background and allows
1906
+ * capturing screenshots with transparency. Defaults to `false`
1907
+ *
1908
+ * - `encoding` : The encoding of the image, can be either base64 or
1909
+ * binary. Defaults to `binary`.
1910
+ *
1911
+ *
1912
+ * NOTE: Screenshots take at least 1/6 second on OS X. See
1913
+ * {@link https://crbug.com/741689} for discussion.
1914
+ * @returns Promise which resolves to buffer or a base64 string (depending on
1915
+ * the value of `encoding`) with captured screenshot.
1916
+ */
1917
+ async screenshot(options = {}) {
1918
+ let screenshotType = null;
1919
+ // options.type takes precedence over inferring the type from options.path
1920
+ // because it may be a 0-length file with no extension created beforehand
1921
+ // (i.e. as a temp file).
1922
+ if (options.type) {
1923
+ const type = options.type;
1924
+ if (type !== 'png' && type !== 'jpeg' && type !== 'webp') {
1925
+ assertNever(type, 'Unknown options.type value: ' + type);
1926
+ }
1927
+ screenshotType = options.type;
1928
+ }
1929
+ else if (options.path) {
1930
+ const filePath = options.path;
1931
+ const extension = filePath
1932
+ .slice(filePath.lastIndexOf('.') + 1)
1933
+ .toLowerCase();
1934
+ if (extension === 'png')
1935
+ screenshotType = 'png';
1936
+ else if (extension === 'jpg' || extension === 'jpeg')
1937
+ screenshotType = 'jpeg';
1938
+ else if (extension === 'webp')
1939
+ screenshotType = 'webp';
1940
+ assert(screenshotType, `Unsupported screenshot type for extension \`.${extension}\``);
1941
+ }
1942
+ if (!screenshotType)
1943
+ screenshotType = 'png';
1944
+ if (options.quality) {
1945
+ assert(screenshotType === 'jpeg' || screenshotType === 'webp', 'options.quality is unsupported for the ' +
1946
+ screenshotType +
1947
+ ' screenshots');
1948
+ assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' +
1949
+ typeof options.quality);
1950
+ assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');
1951
+ assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' +
1952
+ options.quality);
1953
+ }
1954
+ assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');
1955
+ if (options.clip) {
1956
+ assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' +
1957
+ typeof options.clip.x);
1958
+ assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' +
1959
+ typeof options.clip.y);
1960
+ assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' +
1961
+ typeof options.clip.width);
1962
+ assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' +
1963
+ typeof options.clip.height);
1964
+ assert(options.clip.width !== 0, 'Expected options.clip.width not to be 0.');
1965
+ assert(options.clip.height !== 0, 'Expected options.clip.height not to be 0.');
1966
+ }
1967
+ return this._screenshotTaskQueue.postTask(() => this._screenshotTask(screenshotType, options));
1968
+ }
1969
+ async _screenshotTask(format, options) {
1970
+ await this._client.send('Target.activateTarget', {
1971
+ targetId: this._target._targetId,
1972
+ });
1973
+ let clip = options.clip ? processClip(options.clip) : undefined;
1974
+ let { captureBeyondViewport = true } = options;
1975
+ captureBeyondViewport =
1976
+ typeof captureBeyondViewport === 'boolean' ? captureBeyondViewport : true;
1977
+ if (options.fullPage) {
1978
+ const metrics = await this._client.send('Page.getLayoutMetrics');
1979
+ // Fallback to `contentSize` in case of using Firefox.
1980
+ const { width, height } = metrics.cssContentSize || metrics.contentSize;
1981
+ // Overwrite clip for full page.
1982
+ clip = { x: 0, y: 0, width, height, scale: 1 };
1983
+ if (!captureBeyondViewport) {
1984
+ const { isMobile = false, deviceScaleFactor = 1, isLandscape = false, } = this._viewport || {};
1985
+ const screenOrientation = isLandscape
1986
+ ? { angle: 90, type: 'landscapePrimary' }
1987
+ : { angle: 0, type: 'portraitPrimary' };
1988
+ await this._client.send('Emulation.setDeviceMetricsOverride', {
1989
+ mobile: isMobile,
1990
+ width,
1991
+ height,
1992
+ deviceScaleFactor,
1993
+ screenOrientation,
1994
+ });
1995
+ }
1996
+ }
1997
+ const shouldSetDefaultBackground = options.omitBackground && (format === 'png' || format === 'webp');
1998
+ if (shouldSetDefaultBackground) {
1999
+ await this._setTransparentBackgroundColor();
2000
+ }
2001
+ const result = await this._client.send('Page.captureScreenshot', {
2002
+ format,
2003
+ quality: options.quality,
2004
+ clip,
2005
+ captureBeyondViewport,
2006
+ });
2007
+ if (shouldSetDefaultBackground) {
2008
+ await this._resetDefaultBackgroundColor();
2009
+ }
2010
+ if (options.fullPage && this._viewport)
2011
+ await this.setViewport(this._viewport);
2012
+ const buffer = options.encoding === 'base64'
2013
+ ? result.data
2014
+ : Buffer.from(result.data, 'base64');
2015
+ if (options.path) {
2016
+ if (!isNode) {
2017
+ throw new Error('Screenshots can only be written to a file path in a Node environment.');
2018
+ }
2019
+ const fs = await helper.importFSModule();
2020
+ await fs.promises.writeFile(options.path, buffer);
2021
+ }
2022
+ return buffer;
2023
+ function processClip(clip) {
2024
+ const x = Math.round(clip.x);
2025
+ const y = Math.round(clip.y);
2026
+ const width = Math.round(clip.width + clip.x - x);
2027
+ const height = Math.round(clip.height + clip.y - y);
2028
+ return { x, y, width, height, scale: 1 };
2029
+ }
2030
+ }
2031
+ /**
2032
+ * Generatees a PDF of the page with the `print` CSS media type.
2033
+ * @remarks
2034
+ *
2035
+ * NOTE: PDF generation is only supported in Chrome headless mode.
2036
+ *
2037
+ * To generate a PDF with the `screen` media type, call
2038
+ * {@link Page.emulateMediaType | `page.emulateMediaType('screen')`} before
2039
+ * calling `page.pdf()`.
2040
+ *
2041
+ * By default, `page.pdf()` generates a pdf with modified colors for printing.
2042
+ * Use the
2043
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust | `-webkit-print-color-adjust`}
2044
+ * property to force rendering of exact colors.
2045
+ *
2046
+ *
2047
+ * @param options - options for generating the PDF.
2048
+ */
2049
+ async createPDFStream(options = {}) {
2050
+ const { scale = 1, displayHeaderFooter = false, headerTemplate = '', footerTemplate = '', printBackground = false, landscape = false, pageRanges = '', preferCSSPageSize = false, margin = {}, omitBackground = false, timeout = 30000, } = options;
2051
+ let paperWidth = 8.5;
2052
+ let paperHeight = 11;
2053
+ if (options.format) {
2054
+ const format = paperFormats[options.format.toLowerCase()];
2055
+ assert(format, 'Unknown paper format: ' + options.format);
2056
+ paperWidth = format.width;
2057
+ paperHeight = format.height;
2058
+ }
2059
+ else {
2060
+ paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
2061
+ paperHeight =
2062
+ convertPrintParameterToInches(options.height) || paperHeight;
2063
+ }
2064
+ const marginTop = convertPrintParameterToInches(margin.top) || 0;
2065
+ const marginLeft = convertPrintParameterToInches(margin.left) || 0;
2066
+ const marginBottom = convertPrintParameterToInches(margin.bottom) || 0;
2067
+ const marginRight = convertPrintParameterToInches(margin.right) || 0;
2068
+ if (omitBackground) {
2069
+ await this._setTransparentBackgroundColor();
2070
+ }
2071
+ const printCommandPromise = this._client.send('Page.printToPDF', {
2072
+ transferMode: 'ReturnAsStream',
2073
+ landscape,
2074
+ displayHeaderFooter,
2075
+ headerTemplate,
2076
+ footerTemplate,
2077
+ printBackground,
2078
+ scale,
2079
+ paperWidth,
2080
+ paperHeight,
2081
+ marginTop,
2082
+ marginBottom,
2083
+ marginLeft,
2084
+ marginRight,
2085
+ pageRanges,
2086
+ preferCSSPageSize,
2087
+ });
2088
+ const result = await helper.waitWithTimeout(printCommandPromise, 'Page.printToPDF', timeout);
2089
+ if (omitBackground) {
2090
+ await this._resetDefaultBackgroundColor();
2091
+ }
2092
+ return helper.getReadableFromProtocolStream(this._client, result.stream);
2093
+ }
2094
+ /**
2095
+ * @param options -
2096
+ * @returns
2097
+ */
2098
+ async pdf(options = {}) {
2099
+ const { path = undefined } = options;
2100
+ const readable = await this.createPDFStream(options);
2101
+ return await helper.getReadableAsBuffer(readable, path);
2102
+ }
2103
+ /**
2104
+ * @returns The page's title
2105
+ * @remarks
2106
+ * Shortcut for {@link Frame.title | page.mainFrame().title()}.
2107
+ */
2108
+ async title() {
2109
+ return this.mainFrame().title();
2110
+ }
2111
+ async close(options = { runBeforeUnload: undefined }) {
2112
+ assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');
2113
+ const runBeforeUnload = !!options.runBeforeUnload;
2114
+ if (runBeforeUnload) {
2115
+ await this._client.send('Page.close');
2116
+ }
2117
+ else {
2118
+ await this._client._connection.send('Target.closeTarget', {
2119
+ targetId: this._target._targetId,
2120
+ });
2121
+ await this._target._isClosedPromise;
2122
+ }
2123
+ }
2124
+ /**
2125
+ * Indicates that the page has been closed.
2126
+ * @returns
2127
+ */
2128
+ isClosed() {
2129
+ return this._closed;
2130
+ }
2131
+ get mouse() {
2132
+ return this._mouse;
2133
+ }
2134
+ /**
2135
+ * This method fetches an element with `selector`, scrolls it into view if
2136
+ * needed, and then uses {@link Page.mouse} to click in the center of the
2137
+ * element. If there's no element matching `selector`, the method throws an
2138
+ * error.
2139
+ * @remarks Bear in mind that if `click()` triggers a navigation event and
2140
+ * there's a separate `page.waitForNavigation()` promise to be resolved, you
2141
+ * may end up with a race condition that yields unexpected results. The
2142
+ * correct pattern for click and wait for navigation is the following:
2143
+ * ```js
2144
+ * const [response] = await Promise.all([
2145
+ * page.waitForNavigation(waitOptions),
2146
+ * page.click(selector, clickOptions),
2147
+ * ]);
2148
+ * ```
2149
+ * Shortcut for {@link Frame.click | page.mainFrame().click(selector[, options]) }.
2150
+ * @param selector - A `selector` to search for element to click. If there are
2151
+ * multiple elements satisfying the `selector`, the first will be clicked
2152
+ * @param options - `Object`
2153
+ * @returns Promise which resolves when the element matching `selector` is
2154
+ * successfully clicked. The Promise will be rejected if there is no element
2155
+ * matching `selector`.
2156
+ */
2157
+ click(selector, options = {}) {
2158
+ return this.mainFrame().click(selector, options);
2159
+ }
2160
+ /**
2161
+ * This method fetches an element with `selector` and focuses it. If there's no
2162
+ * element matching `selector`, the method throws an error.
2163
+ * @param selector - A
2164
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector }
2165
+ * of an element to focus. If there are multiple elements satisfying the
2166
+ * selector, the first will be focused.
2167
+ * @returns Promise which resolves when the element matching selector is
2168
+ * successfully focused. The promise will be rejected if there is no element
2169
+ * matching selector.
2170
+ * @remarks
2171
+ * Shortcut for {@link Frame.focus | page.mainFrame().focus(selector)}.
2172
+ */
2173
+ focus(selector) {
2174
+ return this.mainFrame().focus(selector);
2175
+ }
2176
+ /**
2177
+ * This method fetches an element with `selector`, scrolls it into view if
2178
+ * needed, and then uses {@link Page.mouse} to hover over the center of the element.
2179
+ * If there's no element matching `selector`, the method throws an error.
2180
+ * @param selector - A
2181
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
2182
+ * to search for element to hover. If there are multiple elements satisfying
2183
+ * the selector, the first will be hovered.
2184
+ * @returns Promise which resolves when the element matching `selector` is
2185
+ * successfully hovered. Promise gets rejected if there's no element matching
2186
+ * `selector`.
2187
+ * @remarks
2188
+ * Shortcut for {@link Page.hover | page.mainFrame().hover(selector)}.
2189
+ */
2190
+ hover(selector) {
2191
+ return this.mainFrame().hover(selector);
2192
+ }
2193
+ /**
2194
+ * Triggers a `change` and `input` event once all the provided options have been
2195
+ * selected. If there's no `<select>` element matching `selector`, the method
2196
+ * throws an error.
2197
+ *
2198
+ * @example
2199
+ * ```js
2200
+ * page.select('select#colors', 'blue'); // single selection
2201
+ * page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
2202
+ * ```
2203
+ * @param selector - A
2204
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | Selector}
2205
+ * to query the page for
2206
+ * @param values - Values of options to select. If the `<select>` has the
2207
+ * `multiple` attribute, all values are considered, otherwise only the first one
2208
+ * is taken into account.
2209
+ * @returns
2210
+ *
2211
+ * @remarks
2212
+ * Shortcut for {@link Frame.select | page.mainFrame().select()}
2213
+ */
2214
+ select(selector, ...values) {
2215
+ return this.mainFrame().select(selector, ...values);
2216
+ }
2217
+ /**
2218
+ * This method fetches an element with `selector`, scrolls it into view if
2219
+ * needed, and then uses {@link Page.touchscreen} to tap in the center of the element.
2220
+ * If there's no element matching `selector`, the method throws an error.
2221
+ * @param selector - A
2222
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | Selector}
2223
+ * to search for element to tap. If there are multiple elements satisfying the
2224
+ * selector, the first will be tapped.
2225
+ * @returns
2226
+ * @remarks
2227
+ * Shortcut for {@link Frame.tap | page.mainFrame().tap(selector)}.
2228
+ */
2229
+ tap(selector) {
2230
+ return this.mainFrame().tap(selector);
2231
+ }
2232
+ /**
2233
+ * Sends a `keydown`, `keypress/input`, and `keyup` event for each character
2234
+ * in the text.
2235
+ *
2236
+ * To press a special key, like `Control` or `ArrowDown`, use {@link Keyboard.press}.
2237
+ * @example
2238
+ * ```
2239
+ * await page.type('#mytextarea', 'Hello');
2240
+ * // Types instantly
2241
+ * await page.type('#mytextarea', 'World', { delay: 100 });
2242
+ * // Types slower, like a user
2243
+ * ```
2244
+ * @param selector - A
2245
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
2246
+ * of an element to type into. If there are multiple elements satisfying the
2247
+ * selector, the first will be used.
2248
+ * @param text - A text to type into a focused element.
2249
+ * @param options - have property `delay` which is the Time to wait between
2250
+ * key presses in milliseconds. Defaults to `0`.
2251
+ * @returns
2252
+ * @remarks
2253
+ */
2254
+ type(selector, text, options) {
2255
+ return this.mainFrame().type(selector, text, options);
2256
+ }
2257
+ /**
2258
+ * @remarks
2259
+ *
2260
+ * This method behaves differently depending on the first parameter. If it's a
2261
+ * `string`, it will be treated as a `selector` or `xpath` (if the string
2262
+ * starts with `//`). This method then is a shortcut for
2263
+ * {@link Page.waitForSelector} or {@link Page.waitForXPath}.
2264
+ *
2265
+ * If the first argument is a function this method is a shortcut for
2266
+ * {@link Page.waitForFunction}.
2267
+ *
2268
+ * If the first argument is a `number`, it's treated as a timeout in
2269
+ * milliseconds and the method returns a promise which resolves after the
2270
+ * timeout.
2271
+ *
2272
+ * @param selectorOrFunctionOrTimeout - a selector, predicate or timeout to
2273
+ * wait for.
2274
+ * @param options - optional waiting parameters.
2275
+ * @param args - arguments to pass to `pageFunction`.
2276
+ *
2277
+ * @deprecated Don't use this method directly. Instead use the more explicit
2278
+ * methods available: {@link Page.waitForSelector},
2279
+ * {@link Page.waitForXPath}, {@link Page.waitForFunction} or
2280
+ * {@link Page.waitForTimeout}.
2281
+ */
2282
+ waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
2283
+ return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
2284
+ }
2285
+ /**
2286
+ * Causes your script to wait for the given number of milliseconds.
2287
+ *
2288
+ * @remarks
2289
+ *
2290
+ * It's generally recommended to not wait for a number of seconds, but instead
2291
+ * use {@link Page.waitForSelector}, {@link Page.waitForXPath} or
2292
+ * {@link Page.waitForFunction} to wait for exactly the conditions you want.
2293
+ *
2294
+ * @example
2295
+ *
2296
+ * Wait for 1 second:
2297
+ *
2298
+ * ```
2299
+ * await page.waitForTimeout(1000);
2300
+ * ```
2301
+ *
2302
+ * @param milliseconds - the number of milliseconds to wait.
2303
+ */
2304
+ waitForTimeout(milliseconds) {
2305
+ return this.mainFrame().waitForTimeout(milliseconds);
2306
+ }
2307
+ /**
2308
+ * Wait for the `selector` to appear in page. If at the moment of calling the
2309
+ * method the `selector` already exists, the method will return immediately. If
2310
+ * the `selector` doesn't appear after the `timeout` milliseconds of waiting, the
2311
+ * function will throw.
2312
+ *
2313
+ * This method works across navigations:
2314
+ * ```js
2315
+ * const puppeteer = require('puppeteer');
2316
+ * (async () => {
2317
+ * const browser = await puppeteer.launch();
2318
+ * const page = await browser.newPage();
2319
+ * let currentURL;
2320
+ * page
2321
+ * .waitForSelector('img')
2322
+ * .then(() => console.log('First URL with image: ' + currentURL));
2323
+ * for (currentURL of [
2324
+ * 'https://example.com',
2325
+ * 'https://google.com',
2326
+ * 'https://bbc.com',
2327
+ * ]) {
2328
+ * await page.goto(currentURL);
2329
+ * }
2330
+ * await browser.close();
2331
+ * })();
2332
+ * ```
2333
+ * @param selector - A
2334
+ * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
2335
+ * of an element to wait for
2336
+ * @param options - Optional waiting parameters
2337
+ * @returns Promise which resolves when element specified by selector string
2338
+ * is added to DOM. Resolves to `null` if waiting for hidden: `true` and
2339
+ * selector is not found in DOM.
2340
+ * @remarks
2341
+ * The optional Parameter in Arguments `options` are :
2342
+ *
2343
+ * - `Visible`: A boolean wait for element to be present in DOM and to be
2344
+ * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
2345
+ * properties. Defaults to `false`.
2346
+ *
2347
+ * - `hidden`: ait for element to not be found in the DOM or to be hidden,
2348
+ * i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to
2349
+ * `false`.
2350
+ *
2351
+ * - `timeout`: maximum time to wait for in milliseconds. Defaults to `30000`
2352
+ * (30 seconds). Pass `0` to disable timeout. The default value can be changed
2353
+ * by using the {@link Page.setDefaultTimeout} method.
2354
+ */
2355
+ waitForSelector(selector, options = {}) {
2356
+ return this.mainFrame().waitForSelector(selector, options);
2357
+ }
2358
+ /**
2359
+ * Wait for the `xpath` to appear in page. If at the moment of calling the
2360
+ * method the `xpath` already exists, the method will return immediately. If
2361
+ * the `xpath` doesn't appear after the `timeout` milliseconds of waiting, the
2362
+ * function will throw.
2363
+ *
2364
+ * This method works across navigation
2365
+ * ```js
2366
+ * const puppeteer = require('puppeteer');
2367
+ * (async () => {
2368
+ * const browser = await puppeteer.launch();
2369
+ * const page = await browser.newPage();
2370
+ * let currentURL;
2371
+ * page
2372
+ * .waitForXPath('//img')
2373
+ * .then(() => console.log('First URL with image: ' + currentURL));
2374
+ * for (currentURL of [
2375
+ * 'https://example.com',
2376
+ * 'https://google.com',
2377
+ * 'https://bbc.com',
2378
+ * ]) {
2379
+ * await page.goto(currentURL);
2380
+ * }
2381
+ * await browser.close();
2382
+ * })();
2383
+ * ```
2384
+ * @param xpath - A
2385
+ * {@link https://developer.mozilla.org/en-US/docs/Web/XPath | xpath} of an
2386
+ * element to wait for
2387
+ * @param options - Optional waiting parameters
2388
+ * @returns Promise which resolves when element specified by xpath string is
2389
+ * added to DOM. Resolves to `null` if waiting for `hidden: true` and xpath is
2390
+ * not found in DOM.
2391
+ * @remarks
2392
+ * The optional Argument `options` have properties:
2393
+ *
2394
+ * - `visible`: A boolean to wait for element to be present in DOM and to be
2395
+ * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
2396
+ * properties. Defaults to `false`.
2397
+ *
2398
+ * - `hidden`: A boolean wait for element to not be found in the DOM or to be
2399
+ * hidden, i.e. have `display: none` or `visibility: hidden` CSS properties.
2400
+ * Defaults to `false`.
2401
+ *
2402
+ * - `timeout`: A number which is maximum time to wait for in milliseconds.
2403
+ * Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default
2404
+ * value can be changed by using the {@link Page.setDefaultTimeout} method.
2405
+ */
2406
+ waitForXPath(xpath, options = {}) {
2407
+ return this.mainFrame().waitForXPath(xpath, options);
2408
+ }
2409
+ /**
2410
+ * The `waitForFunction` can be used to observe viewport size change:
2411
+ *
2412
+ * ```
2413
+ * const puppeteer = require('puppeteer');
2414
+ * (async () => {
2415
+ * const browser = await puppeteer.launch();
2416
+ * const page = await browser.newPage();
2417
+ * const watchDog = page.waitForFunction('window.innerWidth < 100');
2418
+ * await page.setViewport({ width: 50, height: 50 });
2419
+ * await watchDog;
2420
+ * await browser.close();
2421
+ * })();
2422
+ * ```
2423
+ * To pass arguments from node.js to the predicate of `page.waitForFunction` function:
2424
+ * ```
2425
+ * const selector = '.foo';
2426
+ * await page.waitForFunction(
2427
+ * (selector) => !!document.querySelector(selector),
2428
+ * {},
2429
+ * selector
2430
+ * );
2431
+ * ```
2432
+ * The predicate of `page.waitForFunction` can be asynchronous too:
2433
+ * ```
2434
+ * const username = 'github-username';
2435
+ * await page.waitForFunction(
2436
+ * async (username) => {
2437
+ * const githubResponse = await fetch(
2438
+ * `https://api.github.com/users/${username}`
2439
+ * );
2440
+ * const githubUser = await githubResponse.json();
2441
+ * // show the avatar
2442
+ * const img = document.createElement('img');
2443
+ * img.src = githubUser.avatar_url;
2444
+ * // wait 3 seconds
2445
+ * await new Promise((resolve, reject) => setTimeout(resolve, 3000));
2446
+ * img.remove();
2447
+ * },
2448
+ * {},
2449
+ * username
2450
+ * );
2451
+ * ```
2452
+ * @param pageFunction - Function to be evaluated in browser context
2453
+ * @param options - Optional waiting parameters
2454
+ * @param args - Arguments to pass to `pageFunction`
2455
+ * @returns Promise which resolves when the `pageFunction` returns a truthy
2456
+ * value. It resolves to a JSHandle of the truthy value.
2457
+ *
2458
+ * The optional waiting parameter can be:
2459
+ *
2460
+ * - `Polling`: An interval at which the `pageFunction` is executed, defaults to
2461
+ * `raf`. If `polling` is a number, then it is treated as an interval in
2462
+ * milliseconds at which the function would be executed. If polling is a
2463
+ * string, then it can be one of the following values:<br/>
2464
+ * - `raf`: to constantly execute `pageFunction` in `requestAnimationFrame`
2465
+ * callback. This is the tightest polling mode which is suitable to
2466
+ * observe styling changes.<br/>
2467
+ * - `mutation`: to execute pageFunction on every DOM mutation.
2468
+ *
2469
+ * - `timeout`: maximum time to wait for in milliseconds. Defaults to `30000`
2470
+ * (30 seconds). Pass `0` to disable timeout. The default value can be changed
2471
+ * by using the
2472
+ * {@link Page.setDefaultTimeout | page.setDefaultTimeout(timeout)} method.
2473
+ *
2474
+ */
2475
+ waitForFunction(pageFunction, options = {}, ...args) {
2476
+ return this.mainFrame().waitForFunction(pageFunction, options, ...args);
2477
+ }
2478
+ }
2479
+ const supportedMetrics = new Set([
2480
+ 'Timestamp',
2481
+ 'Documents',
2482
+ 'Frames',
2483
+ 'JSEventListeners',
2484
+ 'Nodes',
2485
+ 'LayoutCount',
2486
+ 'RecalcStyleCount',
2487
+ 'LayoutDuration',
2488
+ 'RecalcStyleDuration',
2489
+ 'ScriptDuration',
2490
+ 'TaskDuration',
2491
+ 'JSHeapUsedSize',
2492
+ 'JSHeapTotalSize',
2493
+ ]);
2494
+ const unitToPixels = {
2495
+ px: 1,
2496
+ in: 96,
2497
+ cm: 37.8,
2498
+ mm: 3.78,
2499
+ };
2500
+ function convertPrintParameterToInches(parameter) {
2501
+ if (typeof parameter === 'undefined')
2502
+ return undefined;
2503
+ let pixels;
2504
+ if (helper.isNumber(parameter)) {
2505
+ // Treat numbers as pixel values to be aligned with phantom's paperSize.
2506
+ pixels = /** @type {number} */ parameter;
2507
+ }
2508
+ else if (helper.isString(parameter)) {
2509
+ const text = /** @type {string} */ parameter;
2510
+ let unit = text.substring(text.length - 2).toLowerCase();
2511
+ let valueText = '';
2512
+ if (unitToPixels.hasOwnProperty(unit)) {
2513
+ valueText = text.substring(0, text.length - 2);
2514
+ }
2515
+ else {
2516
+ // In case of unknown unit try to parse the whole parameter as number of pixels.
2517
+ // This is consistent with phantom's paperSize behavior.
2518
+ unit = 'px';
2519
+ valueText = text;
2520
+ }
2521
+ const value = Number(valueText);
2522
+ assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
2523
+ pixels = value * unitToPixels[unit];
2524
+ }
2525
+ else {
2526
+ throw new Error('page.pdf() Cannot handle parameter type: ' + typeof parameter);
2527
+ }
2528
+ return pixels / 96;
2529
+ }
2423
2530
  //# sourceMappingURL=Page.js.map