isomorfeus-puppetmaster 0.5.5 → 0.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (710) hide show
  1. checksums.yaml +4 -4
  2. data/lib/isomorfeus/puppetmaster/console_message.rb +18 -18
  3. data/lib/isomorfeus/puppetmaster/cookie.rb +46 -46
  4. data/lib/isomorfeus/puppetmaster/driver/puppeteer.rb +413 -415
  5. data/lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb +953 -953
  6. data/lib/isomorfeus/puppetmaster/driver/puppeteer_node.rb +851 -851
  7. data/lib/isomorfeus/puppetmaster/errors.rb +90 -90
  8. data/lib/isomorfeus/puppetmaster/iframe.rb +16 -16
  9. data/lib/isomorfeus/puppetmaster/node/content_editable.rb +17 -17
  10. data/lib/isomorfeus/puppetmaster/node/input.rb +20 -20
  11. data/lib/isomorfeus/puppetmaster/node/select.rb +35 -35
  12. data/lib/isomorfeus/puppetmaster/node.rb +279 -279
  13. data/lib/isomorfeus/puppetmaster/request.rb +16 -16
  14. data/lib/isomorfeus/puppetmaster/response.rb +25 -25
  15. data/lib/isomorfeus/puppetmaster/self_forwardable.rb +38 -38
  16. data/lib/isomorfeus/puppetmaster/version.rb +3 -3
  17. data/lib/isomorfeus/puppetmaster.rb +85 -85
  18. data/lib/isomorfeus-puppetmaster.rb +1 -0
  19. data/node_modules/.bin/extract-zip +12 -12
  20. data/node_modules/.bin/extract-zip.ps1 +28 -28
  21. data/node_modules/.bin/rimraf +12 -12
  22. data/node_modules/.bin/rimraf.ps1 +28 -28
  23. data/node_modules/.package-lock.json +530 -585
  24. data/node_modules/@types/node/LICENSE +21 -21
  25. data/node_modules/@types/node/assert/strict.d.ts +8 -8
  26. data/node_modules/@types/node/assert.d.ts +912 -912
  27. data/node_modules/@types/node/async_hooks.d.ts +497 -497
  28. data/node_modules/@types/node/buffer.d.ts +2142 -2142
  29. data/node_modules/@types/node/child_process.d.ts +1355 -1355
  30. data/node_modules/@types/node/cluster.d.ts +414 -414
  31. data/node_modules/@types/node/console.d.ts +407 -407
  32. data/node_modules/@types/node/constants.d.ts +18 -18
  33. data/node_modules/@types/node/crypto.d.ts +3224 -3224
  34. data/node_modules/@types/node/dgram.d.ts +545 -545
  35. data/node_modules/@types/node/diagnostics_channel.d.ts +128 -128
  36. data/node_modules/@types/node/dns/promises.d.ts +357 -357
  37. data/node_modules/@types/node/dns.d.ts +643 -643
  38. data/node_modules/@types/node/domain.d.ts +169 -169
  39. data/node_modules/@types/node/events.d.ts +623 -623
  40. data/node_modules/@types/node/fs/promises.d.ts +997 -997
  41. data/node_modules/@types/node/fs.d.ts +3723 -3723
  42. data/node_modules/@types/node/globals.d.ts +285 -285
  43. data/node_modules/@types/node/globals.global.d.ts +1 -1
  44. data/node_modules/@types/node/http.d.ts +1358 -1358
  45. data/node_modules/@types/node/http2.d.ts +2100 -2100
  46. data/node_modules/@types/node/https.d.ts +391 -391
  47. data/node_modules/@types/node/index.d.ts +131 -131
  48. data/node_modules/@types/node/inspector.d.ts +2738 -2738
  49. data/node_modules/@types/node/module.d.ts +114 -114
  50. data/node_modules/@types/node/net.d.ts +783 -783
  51. data/node_modules/@types/node/os.d.ts +455 -455
  52. data/node_modules/@types/node/package.json +229 -229
  53. data/node_modules/@types/node/path.d.ts +172 -172
  54. data/node_modules/@types/node/perf_hooks.d.ts +555 -555
  55. data/node_modules/@types/node/process.d.ts +1477 -1477
  56. data/node_modules/@types/node/punycode.d.ts +117 -117
  57. data/node_modules/@types/node/querystring.d.ts +131 -131
  58. data/node_modules/@types/node/readline.d.ts +542 -542
  59. data/node_modules/@types/node/repl.d.ts +424 -424
  60. data/node_modules/@types/node/stream/consumers.d.ts +24 -24
  61. data/node_modules/@types/node/stream/promises.d.ts +42 -42
  62. data/node_modules/@types/node/stream/web.d.ts +6 -6
  63. data/node_modules/@types/node/stream.d.ts +1181 -1181
  64. data/node_modules/@types/node/string_decoder.d.ts +67 -67
  65. data/node_modules/@types/node/timers/promises.d.ts +68 -68
  66. data/node_modules/@types/node/timers.d.ts +94 -94
  67. data/node_modules/@types/node/tls.d.ts +1019 -1019
  68. data/node_modules/@types/node/trace_events.d.ts +161 -161
  69. data/node_modules/@types/node/tty.d.ts +206 -206
  70. data/node_modules/@types/node/url.d.ts +798 -798
  71. data/node_modules/@types/node/util.d.ts +1556 -1556
  72. data/node_modules/@types/node/v8.d.ts +378 -378
  73. data/node_modules/@types/node/vm.d.ts +504 -504
  74. data/node_modules/@types/node/wasi.d.ts +153 -153
  75. data/node_modules/@types/node/worker_threads.d.ts +649 -649
  76. data/node_modules/@types/node/zlib.d.ts +517 -517
  77. data/node_modules/@types/yauzl/LICENSE +21 -21
  78. data/node_modules/@types/yauzl/index.d.ts +98 -98
  79. data/node_modules/@types/yauzl/package.json +26 -26
  80. data/node_modules/agent-base/README.md +145 -145
  81. data/node_modules/agent-base/dist/src/index.d.ts +78 -78
  82. data/node_modules/agent-base/dist/src/index.js +202 -202
  83. data/node_modules/agent-base/dist/src/promisify.d.ts +4 -4
  84. data/node_modules/agent-base/dist/src/promisify.js +17 -17
  85. data/node_modules/agent-base/package.json +64 -64
  86. data/node_modules/agent-base/src/index.ts +345 -345
  87. data/node_modules/agent-base/src/promisify.ts +33 -33
  88. data/node_modules/balanced-match/.github/FUNDING.yml +2 -2
  89. data/node_modules/balanced-match/LICENSE.md +21 -21
  90. data/node_modules/balanced-match/README.md +97 -97
  91. data/node_modules/balanced-match/index.js +62 -62
  92. data/node_modules/balanced-match/package.json +48 -48
  93. data/node_modules/base64-js/LICENSE +21 -21
  94. data/node_modules/base64-js/README.md +34 -34
  95. data/node_modules/base64-js/index.d.ts +3 -3
  96. data/node_modules/base64-js/index.js +150 -150
  97. data/node_modules/base64-js/package.json +47 -47
  98. data/node_modules/bl/.travis.yml +17 -17
  99. data/node_modules/bl/BufferList.js +396 -396
  100. data/node_modules/bl/LICENSE.md +13 -13
  101. data/node_modules/bl/README.md +247 -247
  102. data/node_modules/bl/bl.js +84 -84
  103. data/node_modules/bl/package.json +37 -37
  104. data/node_modules/bl/test/convert.js +21 -21
  105. data/node_modules/bl/test/indexOf.js +492 -492
  106. data/node_modules/bl/test/isBufferList.js +32 -32
  107. data/node_modules/bl/test/test.js +869 -869
  108. data/node_modules/brace-expansion/LICENSE +21 -21
  109. data/node_modules/brace-expansion/README.md +129 -129
  110. data/node_modules/brace-expansion/index.js +201 -201
  111. data/node_modules/brace-expansion/package.json +47 -47
  112. data/node_modules/buffer/AUTHORS.md +70 -70
  113. data/node_modules/buffer/LICENSE +21 -21
  114. data/node_modules/buffer/README.md +410 -410
  115. data/node_modules/buffer/index.d.ts +186 -186
  116. data/node_modules/buffer/index.js +1817 -1817
  117. data/node_modules/buffer/package.json +96 -96
  118. data/node_modules/buffer-crc32/LICENSE +19 -19
  119. data/node_modules/buffer-crc32/README.md +47 -47
  120. data/node_modules/buffer-crc32/index.js +111 -111
  121. data/node_modules/buffer-crc32/package.json +39 -39
  122. data/node_modules/chownr/LICENSE +15 -15
  123. data/node_modules/chownr/README.md +3 -3
  124. data/node_modules/chownr/chownr.js +167 -167
  125. data/node_modules/chownr/package.json +29 -29
  126. data/node_modules/concat-map/.travis.yml +4 -4
  127. data/node_modules/concat-map/LICENSE +18 -18
  128. data/node_modules/concat-map/README.markdown +62 -62
  129. data/node_modules/concat-map/example/map.js +6 -6
  130. data/node_modules/concat-map/index.js +13 -13
  131. data/node_modules/concat-map/package.json +43 -43
  132. data/node_modules/concat-map/test/map.js +39 -39
  133. data/node_modules/debug/LICENSE +19 -19
  134. data/node_modules/debug/README.md +455 -455
  135. data/node_modules/debug/package.json +59 -59
  136. data/node_modules/debug/src/browser.js +269 -269
  137. data/node_modules/debug/src/common.js +274 -274
  138. data/node_modules/debug/src/index.js +10 -10
  139. data/node_modules/debug/src/node.js +263 -263
  140. data/node_modules/devtools-protocol/LICENSE +27 -27
  141. data/node_modules/devtools-protocol/README.md +12 -12
  142. data/node_modules/devtools-protocol/json/browser_protocol.json +20985 -20640
  143. data/node_modules/devtools-protocol/json/js_protocol.json +3531 -3580
  144. data/node_modules/devtools-protocol/package.json +17 -18
  145. data/node_modules/devtools-protocol/pdl/browser_protocol.pdl +9849 -9637
  146. data/node_modules/devtools-protocol/pdl/js_protocol.pdl +1653 -1678
  147. data/node_modules/devtools-protocol/types/protocol-mapping.d.ts +4333 -4321
  148. data/node_modules/devtools-protocol/types/protocol-proxy-api.d.ts +3695 -3683
  149. data/node_modules/devtools-protocol/types/protocol.d.ts +15714 -15538
  150. data/node_modules/end-of-stream/LICENSE +20 -20
  151. data/node_modules/end-of-stream/README.md +54 -54
  152. data/node_modules/end-of-stream/index.js +94 -94
  153. data/node_modules/end-of-stream/package.json +37 -37
  154. data/node_modules/extract-zip/LICENSE +23 -23
  155. data/node_modules/extract-zip/cli.js +19 -19
  156. data/node_modules/extract-zip/index.d.ts +21 -21
  157. data/node_modules/extract-zip/index.js +173 -173
  158. data/node_modules/extract-zip/package.json +80 -80
  159. data/node_modules/extract-zip/readme.md +57 -57
  160. data/node_modules/fd-slicer/.npmignore +2 -2
  161. data/node_modules/fd-slicer/.travis.yml +7 -7
  162. data/node_modules/fd-slicer/CHANGELOG.md +49 -49
  163. data/node_modules/fd-slicer/LICENSE +21 -21
  164. data/node_modules/fd-slicer/README.md +199 -199
  165. data/node_modules/fd-slicer/index.js +296 -296
  166. data/node_modules/fd-slicer/package.json +36 -36
  167. data/node_modules/fd-slicer/test/test.js +350 -350
  168. data/node_modules/find-up/index.d.ts +137 -137
  169. data/node_modules/find-up/index.js +89 -89
  170. data/node_modules/find-up/license +9 -9
  171. data/node_modules/find-up/package.json +53 -53
  172. data/node_modules/find-up/readme.md +156 -156
  173. data/node_modules/fs-constants/LICENSE +21 -21
  174. data/node_modules/fs-constants/README.md +26 -26
  175. data/node_modules/fs-constants/browser.js +1 -1
  176. data/node_modules/fs-constants/index.js +1 -1
  177. data/node_modules/fs-constants/package.json +19 -19
  178. data/node_modules/fs.realpath/LICENSE +43 -43
  179. data/node_modules/fs.realpath/README.md +33 -33
  180. data/node_modules/fs.realpath/index.js +66 -66
  181. data/node_modules/fs.realpath/old.js +303 -303
  182. data/node_modules/fs.realpath/package.json +26 -26
  183. data/node_modules/get-stream/buffer-stream.js +52 -52
  184. data/node_modules/get-stream/index.d.ts +108 -108
  185. data/node_modules/get-stream/index.js +60 -60
  186. data/node_modules/get-stream/license +9 -9
  187. data/node_modules/get-stream/package.json +50 -50
  188. data/node_modules/get-stream/readme.md +124 -124
  189. data/node_modules/glob/LICENSE +21 -21
  190. data/node_modules/glob/README.md +375 -375
  191. data/node_modules/glob/changelog.md +67 -67
  192. data/node_modules/glob/common.js +234 -234
  193. data/node_modules/glob/glob.js +788 -788
  194. data/node_modules/glob/package.json +51 -51
  195. data/node_modules/glob/sync.js +484 -484
  196. data/node_modules/https-proxy-agent/README.md +137 -137
  197. data/node_modules/https-proxy-agent/dist/agent.d.ts +30 -30
  198. data/node_modules/https-proxy-agent/dist/agent.js +179 -179
  199. data/node_modules/https-proxy-agent/dist/index.d.ts +23 -23
  200. data/node_modules/https-proxy-agent/dist/index.js +13 -13
  201. data/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts +7 -7
  202. data/node_modules/https-proxy-agent/dist/parse-proxy-response.js +65 -65
  203. data/node_modules/https-proxy-agent/package.json +56 -56
  204. data/node_modules/ieee754/LICENSE +11 -11
  205. data/node_modules/ieee754/README.md +51 -51
  206. data/node_modules/ieee754/index.d.ts +9 -9
  207. data/node_modules/ieee754/index.js +85 -85
  208. data/node_modules/ieee754/package.json +52 -52
  209. data/node_modules/inflight/LICENSE +15 -15
  210. data/node_modules/inflight/README.md +37 -37
  211. data/node_modules/inflight/inflight.js +54 -54
  212. data/node_modules/inflight/package.json +29 -29
  213. data/node_modules/inherits/LICENSE +16 -16
  214. data/node_modules/inherits/README.md +42 -42
  215. data/node_modules/inherits/inherits.js +9 -9
  216. data/node_modules/inherits/inherits_browser.js +27 -27
  217. data/node_modules/inherits/package.json +29 -29
  218. data/node_modules/locate-path/index.d.ts +83 -83
  219. data/node_modules/locate-path/index.js +65 -65
  220. data/node_modules/locate-path/license +9 -9
  221. data/node_modules/locate-path/package.json +45 -45
  222. data/node_modules/locate-path/readme.md +122 -122
  223. data/node_modules/minimatch/LICENSE +15 -15
  224. data/node_modules/minimatch/README.md +209 -209
  225. data/node_modules/minimatch/minimatch.js +923 -923
  226. data/node_modules/minimatch/package.json +30 -30
  227. data/node_modules/mkdirp-classic/LICENSE +21 -21
  228. data/node_modules/mkdirp-classic/README.md +18 -18
  229. data/node_modules/mkdirp-classic/index.js +98 -98
  230. data/node_modules/mkdirp-classic/package.json +18 -18
  231. data/node_modules/ms/index.js +162 -162
  232. data/node_modules/ms/license.md +21 -21
  233. data/node_modules/ms/package.json +37 -37
  234. data/node_modules/ms/readme.md +60 -60
  235. data/node_modules/node-fetch/LICENSE.md +22 -22
  236. data/node_modules/node-fetch/README.md +590 -590
  237. data/node_modules/node-fetch/browser.js +24 -24
  238. data/node_modules/node-fetch/lib/index.es.js +1662 -1662
  239. data/node_modules/node-fetch/lib/index.js +1671 -1671
  240. data/node_modules/node-fetch/lib/index.mjs +1660 -1660
  241. data/node_modules/node-fetch/package.json +68 -68
  242. data/node_modules/once/LICENSE +15 -15
  243. data/node_modules/once/README.md +79 -79
  244. data/node_modules/once/once.js +42 -42
  245. data/node_modules/once/package.json +33 -33
  246. data/node_modules/p-limit/index.d.ts +38 -38
  247. data/node_modules/p-limit/index.js +57 -57
  248. data/node_modules/p-limit/license +9 -9
  249. data/node_modules/p-limit/package.json +52 -52
  250. data/node_modules/p-limit/readme.md +101 -101
  251. data/node_modules/p-locate/index.d.ts +64 -64
  252. data/node_modules/p-locate/index.js +52 -52
  253. data/node_modules/p-locate/license +9 -9
  254. data/node_modules/p-locate/package.json +53 -53
  255. data/node_modules/p-locate/readme.md +90 -90
  256. data/node_modules/p-try/index.d.ts +39 -39
  257. data/node_modules/p-try/index.js +9 -9
  258. data/node_modules/p-try/license +9 -9
  259. data/node_modules/p-try/package.json +42 -42
  260. data/node_modules/p-try/readme.md +58 -58
  261. data/node_modules/path-exists/index.d.ts +28 -28
  262. data/node_modules/path-exists/index.js +23 -23
  263. data/node_modules/path-exists/license +9 -9
  264. data/node_modules/path-exists/package.json +39 -39
  265. data/node_modules/path-exists/readme.md +52 -52
  266. data/node_modules/path-is-absolute/index.js +20 -20
  267. data/node_modules/path-is-absolute/license +21 -21
  268. data/node_modules/path-is-absolute/package.json +43 -43
  269. data/node_modules/path-is-absolute/readme.md +59 -59
  270. data/node_modules/pend/LICENSE +23 -23
  271. data/node_modules/pend/README.md +41 -41
  272. data/node_modules/pend/index.js +55 -55
  273. data/node_modules/pend/package.json +18 -18
  274. data/node_modules/pend/test.js +137 -137
  275. data/node_modules/pkg-dir/index.d.ts +44 -44
  276. data/node_modules/pkg-dir/index.js +17 -17
  277. data/node_modules/pkg-dir/license +9 -9
  278. data/node_modules/pkg-dir/package.json +56 -56
  279. data/node_modules/pkg-dir/readme.md +66 -66
  280. data/node_modules/progress/CHANGELOG.md +115 -115
  281. data/node_modules/progress/LICENSE +22 -22
  282. data/node_modules/progress/Makefile +8 -8
  283. data/node_modules/progress/Readme.md +146 -146
  284. data/node_modules/progress/index.js +1 -1
  285. data/node_modules/progress/lib/node-progress.js +236 -236
  286. data/node_modules/progress/package.json +26 -26
  287. data/node_modules/proxy-from-env/.eslintrc +29 -29
  288. data/node_modules/proxy-from-env/.travis.yml +10 -10
  289. data/node_modules/proxy-from-env/LICENSE +20 -20
  290. data/node_modules/proxy-from-env/README.md +131 -131
  291. data/node_modules/proxy-from-env/index.js +108 -108
  292. data/node_modules/proxy-from-env/package.json +34 -34
  293. data/node_modules/proxy-from-env/test.js +483 -483
  294. data/node_modules/pump/.travis.yml +5 -5
  295. data/node_modules/pump/LICENSE +20 -20
  296. data/node_modules/pump/README.md +65 -65
  297. data/node_modules/pump/index.js +82 -82
  298. data/node_modules/pump/package.json +24 -24
  299. data/node_modules/pump/test-browser.js +66 -66
  300. data/node_modules/pump/test-node.js +53 -53
  301. data/node_modules/puppeteer-core/CHANGELOG.md +319 -290
  302. data/node_modules/puppeteer-core/LICENSE +202 -202
  303. data/node_modules/puppeteer-core/README.md +481 -481
  304. data/node_modules/puppeteer-core/cjs-entry-core.js +29 -29
  305. data/node_modules/puppeteer-core/cjs-entry.js +29 -29
  306. data/node_modules/puppeteer-core/install.js +89 -89
  307. data/node_modules/puppeteer-core/lib/cjs/puppeteer/api-docs-entry.d.ts +110 -110
  308. data/node_modules/puppeteer-core/lib/cjs/puppeteer/api-docs-entry.js +80 -80
  309. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Accessibility.d.ts +175 -175
  310. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Accessibility.js +360 -360
  311. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.d.ts +20 -20
  312. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.js +84 -84
  313. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/AriaQueryHandler.js.map +1 -1
  314. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Browser.d.ts +455 -455
  315. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Browser.js +540 -540
  316. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserConnector.d.ts +53 -53
  317. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserConnector.js +97 -97
  318. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserWebSocketTransport.d.ts +25 -25
  319. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/BrowserWebSocketTransport.js +34 -34
  320. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.d.ts +135 -135
  321. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.js +298 -298
  322. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConnectionTransport.d.ts +24 -24
  323. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConnectionTransport.js +17 -17
  324. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConsoleMessage.d.ts +72 -72
  325. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ConsoleMessage.js +64 -64
  326. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Coverage.d.ts +204 -204
  327. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Coverage.js +335 -335
  328. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DOMWorld.d.ts +175 -175
  329. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DOMWorld.js +662 -662
  330. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Debug.d.ts +52 -52
  331. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Debug.js +81 -81
  332. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DeviceDescriptors.d.ts +40 -40
  333. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DeviceDescriptors.js +1070 -1070
  334. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Dialog.d.ts +74 -74
  335. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Dialog.js +97 -97
  336. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EmulationManager.d.ts +24 -24
  337. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EmulationManager.js +37 -37
  338. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Errors.d.ts +50 -50
  339. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Errors.js +56 -56
  340. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EvalTypes.d.ts +60 -60
  341. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EvalTypes.js +17 -17
  342. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.d.ts +92 -92
  343. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js +116 -116
  344. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Events.d.ts +81 -81
  345. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Events.js +86 -86
  346. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ExecutionContext.d.ts +193 -193
  347. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/ExecutionContext.js +321 -321
  348. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FileChooser.d.ts +58 -58
  349. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FileChooser.js +71 -71
  350. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FrameManager.d.ts +744 -744
  351. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FrameManager.js +1047 -1047
  352. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/FrameManager.js.map +1 -1
  353. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest.d.ts +350 -345
  354. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest.d.ts.map +1 -1
  355. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest.js +549 -549
  356. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest.js.map +1 -1
  357. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPResponse.d.ts +134 -125
  358. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPResponse.d.ts.map +1 -1
  359. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPResponse.js +184 -164
  360. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/HTTPResponse.js.map +1 -1
  361. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Input.d.ts +358 -358
  362. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Input.js +543 -543
  363. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/JSHandle.d.ts +490 -490
  364. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/JSHandle.js +827 -827
  365. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.d.ts +65 -65
  366. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.d.ts.map +1 -1
  367. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.js +149 -148
  368. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.js.map +1 -1
  369. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkConditions.d.ts +26 -26
  370. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkConditions.js +33 -33
  371. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManager.d.ts +126 -97
  372. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManager.d.ts.map +1 -1
  373. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManager.js +467 -342
  374. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/NetworkManager.js.map +1 -1
  375. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.d.ts +161 -161
  376. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PDFOptions.js +34 -34
  377. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.d.ts +2055 -2055
  378. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.js +2533 -2533
  379. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Product.d.ts +20 -20
  380. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Product.js +17 -17
  381. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Puppeteer.d.ts +159 -159
  382. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Puppeteer.js +161 -161
  383. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PuppeteerViewport.d.ts +51 -51
  384. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/PuppeteerViewport.js +2 -2
  385. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/QueryHandler.d.ts +64 -64
  386. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/QueryHandler.js +165 -165
  387. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/SecurityDetails.d.ts +60 -60
  388. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/SecurityDetails.js +76 -76
  389. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Target.d.ts +100 -100
  390. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Target.js +145 -145
  391. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.d.ts +20 -20
  392. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TaskQueue.js +29 -29
  393. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TimeoutSettings.d.ts +27 -27
  394. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/TimeoutSettings.js +47 -47
  395. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Tracing.d.ts +46 -46
  396. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Tracing.js +109 -109
  397. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.d.ts +39 -39
  398. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.js +406 -406
  399. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WebWorker.d.ts +98 -98
  400. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WebWorker.js +112 -112
  401. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/assert.d.ts +22 -22
  402. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/assert.js +33 -33
  403. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/fetch.d.ts +16 -16
  404. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/fetch.js +43 -43
  405. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/helper.d.ts +84 -84
  406. data/node_modules/puppeteer-core/lib/cjs/puppeteer/common/helper.js +327 -327
  407. data/node_modules/puppeteer-core/lib/cjs/puppeteer/environment.d.ts +16 -16
  408. data/node_modules/puppeteer-core/lib/cjs/puppeteer/environment.js +19 -19
  409. data/node_modules/puppeteer-core/lib/cjs/puppeteer/global.d.ts +16 -16
  410. data/node_modules/puppeteer-core/lib/cjs/puppeteer/global.js +2 -2
  411. data/node_modules/puppeteer-core/lib/cjs/puppeteer/initialize-node.d.ts +17 -17
  412. data/node_modules/puppeteer-core/lib/cjs/puppeteer/initialize-node.js +44 -44
  413. data/node_modules/puppeteer-core/lib/cjs/puppeteer/initialize-web.d.ts +17 -17
  414. data/node_modules/puppeteer-core/lib/cjs/puppeteer/initialize-web.js +26 -26
  415. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserFetcher.d.ts +133 -133
  416. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserFetcher.js +500 -500
  417. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.d.ts +40 -39
  418. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.d.ts.map +1 -1
  419. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.js +256 -230
  420. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/BrowserRunner.js.map +1 -1
  421. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/LaunchOptions.d.ts +134 -134
  422. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/LaunchOptions.js +17 -17
  423. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Launcher.d.ts +16 -16
  424. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Launcher.d.ts.map +1 -1
  425. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Launcher.js +655 -588
  426. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Launcher.js.map +1 -1
  427. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.d.ts +26 -26
  428. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.js +47 -47
  429. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/PipeTransport.d.ts +29 -29
  430. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/PipeTransport.js +64 -64
  431. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Puppeteer.d.ts +153 -153
  432. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/Puppeteer.js +188 -188
  433. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/install.d.ts +17 -17
  434. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node/install.js +173 -173
  435. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node-puppeteer-core.d.ts +17 -17
  436. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node-puppeteer-core.js +24 -24
  437. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node.d.ts +17 -17
  438. data/node_modules/puppeteer-core/lib/cjs/puppeteer/node.js +23 -23
  439. data/node_modules/puppeteer-core/lib/cjs/puppeteer/revisions.d.ts +21 -21
  440. data/node_modules/puppeteer-core/lib/cjs/puppeteer/revisions.js +22 -22
  441. data/node_modules/puppeteer-core/lib/cjs/puppeteer/web.d.ts +17 -17
  442. data/node_modules/puppeteer-core/lib/cjs/puppeteer/web.js +23 -23
  443. data/node_modules/puppeteer-core/lib/cjs/vendor/mitt/src/index.d.ts +27 -27
  444. data/node_modules/puppeteer-core/lib/cjs/vendor/mitt/src/index.js +56 -56
  445. data/node_modules/puppeteer-core/lib/esm/puppeteer/api-docs-entry.d.ts +110 -110
  446. data/node_modules/puppeteer-core/lib/esm/puppeteer/api-docs-entry.js +80 -80
  447. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Accessibility.d.ts +175 -175
  448. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Accessibility.js +356 -356
  449. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/AriaQueryHandler.d.ts +20 -20
  450. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/AriaQueryHandler.js +81 -81
  451. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/AriaQueryHandler.js.map +1 -1
  452. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Browser.d.ts +455 -455
  453. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Browser.js +535 -535
  454. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/BrowserConnector.d.ts +53 -53
  455. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/BrowserConnector.js +74 -74
  456. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/BrowserWebSocketTransport.d.ts +25 -25
  457. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/BrowserWebSocketTransport.js +30 -30
  458. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Connection.d.ts +135 -135
  459. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Connection.js +293 -293
  460. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ConnectionTransport.d.ts +24 -24
  461. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ConnectionTransport.js +16 -16
  462. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ConsoleMessage.d.ts +72 -72
  463. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ConsoleMessage.js +60 -60
  464. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Coverage.d.ts +204 -204
  465. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Coverage.js +329 -329
  466. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DOMWorld.d.ts +175 -175
  467. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DOMWorld.js +657 -657
  468. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Debug.d.ts +52 -52
  469. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Debug.js +77 -77
  470. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DeviceDescriptors.d.ts +40 -40
  471. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/DeviceDescriptors.js +1067 -1067
  472. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Dialog.d.ts +74 -74
  473. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Dialog.js +93 -93
  474. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EmulationManager.d.ts +24 -24
  475. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EmulationManager.js +33 -33
  476. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Errors.d.ts +50 -50
  477. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Errors.js +50 -50
  478. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EvalTypes.d.ts +60 -60
  479. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EvalTypes.js +16 -16
  480. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EventEmitter.d.ts +92 -92
  481. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/EventEmitter.js +109 -109
  482. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Events.d.ts +81 -81
  483. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Events.js +83 -83
  484. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ExecutionContext.d.ts +193 -193
  485. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/ExecutionContext.js +317 -317
  486. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FileChooser.d.ts +58 -58
  487. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FileChooser.js +67 -67
  488. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FrameManager.d.ts +744 -744
  489. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FrameManager.js +1042 -1042
  490. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/FrameManager.js.map +1 -1
  491. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPRequest.d.ts +350 -345
  492. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPRequest.d.ts.map +1 -1
  493. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPRequest.js +545 -545
  494. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPRequest.js.map +1 -1
  495. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPResponse.d.ts +134 -125
  496. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPResponse.d.ts.map +1 -1
  497. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPResponse.js +180 -160
  498. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/HTTPResponse.js.map +1 -1
  499. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Input.d.ts +358 -358
  500. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Input.js +537 -537
  501. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/JSHandle.d.ts +490 -490
  502. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/JSHandle.js +802 -802
  503. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/LifecycleWatcher.d.ts +65 -65
  504. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/LifecycleWatcher.d.ts.map +1 -1
  505. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/LifecycleWatcher.js +145 -144
  506. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/LifecycleWatcher.js.map +1 -1
  507. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkConditions.d.ts +26 -26
  508. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkConditions.js +30 -30
  509. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkManager.d.ts +126 -97
  510. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkManager.d.ts.map +1 -1
  511. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkManager.js +463 -338
  512. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/NetworkManager.js.map +1 -1
  513. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PDFOptions.d.ts +161 -161
  514. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PDFOptions.js +31 -31
  515. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Page.d.ts +2055 -2055
  516. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Page.js +2529 -2529
  517. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Product.d.ts +20 -20
  518. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Product.js +16 -16
  519. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Puppeteer.d.ts +159 -159
  520. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Puppeteer.js +157 -157
  521. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PuppeteerViewport.d.ts +51 -51
  522. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/PuppeteerViewport.js +1 -1
  523. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/QueryHandler.d.ts +64 -64
  524. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/QueryHandler.js +157 -157
  525. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/SecurityDetails.d.ts +60 -60
  526. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/SecurityDetails.js +72 -72
  527. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Target.d.ts +100 -100
  528. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Target.js +141 -141
  529. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TaskQueue.d.ts +20 -20
  530. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TaskQueue.js +25 -25
  531. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TimeoutSettings.d.ts +27 -27
  532. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/TimeoutSettings.js +43 -43
  533. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Tracing.d.ts +46 -46
  534. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/Tracing.js +105 -105
  535. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/USKeyboardLayout.d.ts +39 -39
  536. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/USKeyboardLayout.js +403 -403
  537. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/WebWorker.d.ts +98 -98
  538. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/WebWorker.js +108 -108
  539. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/assert.d.ts +22 -22
  540. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/assert.js +28 -28
  541. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/fetch.d.ts +16 -16
  542. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/fetch.js +20 -20
  543. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/helper.d.ts +84 -84
  544. data/node_modules/puppeteer-core/lib/esm/puppeteer/common/helper.js +305 -305
  545. data/node_modules/puppeteer-core/lib/esm/puppeteer/environment.d.ts +16 -16
  546. data/node_modules/puppeteer-core/lib/esm/puppeteer/environment.js +16 -16
  547. data/node_modules/puppeteer-core/lib/esm/puppeteer/global.d.ts +16 -16
  548. data/node_modules/puppeteer-core/lib/esm/puppeteer/global.js +1 -1
  549. data/node_modules/puppeteer-core/lib/esm/puppeteer/initialize-node.d.ts +17 -17
  550. data/node_modules/puppeteer-core/lib/esm/puppeteer/initialize-node.js +37 -37
  551. data/node_modules/puppeteer-core/lib/esm/puppeteer/initialize-web.d.ts +17 -17
  552. data/node_modules/puppeteer-core/lib/esm/puppeteer/initialize-web.js +22 -22
  553. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserFetcher.d.ts +133 -133
  554. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserFetcher.js +474 -474
  555. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.d.ts +40 -39
  556. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.d.ts.map +1 -1
  557. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js +230 -204
  558. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js.map +1 -1
  559. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/LaunchOptions.d.ts +134 -134
  560. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/LaunchOptions.js +16 -16
  561. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Launcher.d.ts +16 -16
  562. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Launcher.d.ts.map +1 -1
  563. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Launcher.js +633 -566
  564. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Launcher.js.map +1 -1
  565. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/NodeWebSocketTransport.d.ts +26 -26
  566. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/NodeWebSocketTransport.js +40 -40
  567. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/PipeTransport.d.ts +29 -29
  568. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/PipeTransport.js +60 -60
  569. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Puppeteer.d.ts +153 -153
  570. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/Puppeteer.js +181 -181
  571. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/install.d.ts +17 -17
  572. data/node_modules/puppeteer-core/lib/esm/puppeteer/node/install.js +165 -165
  573. data/node_modules/puppeteer-core/lib/esm/puppeteer/node-puppeteer-core.d.ts +17 -17
  574. data/node_modules/puppeteer-core/lib/esm/puppeteer/node-puppeteer-core.js +22 -22
  575. data/node_modules/puppeteer-core/lib/esm/puppeteer/node.d.ts +17 -17
  576. data/node_modules/puppeteer-core/lib/esm/puppeteer/node.js +21 -21
  577. data/node_modules/puppeteer-core/lib/esm/puppeteer/revisions.d.ts +21 -21
  578. data/node_modules/puppeteer-core/lib/esm/puppeteer/revisions.js +19 -19
  579. data/node_modules/puppeteer-core/lib/esm/puppeteer/web.d.ts +17 -17
  580. data/node_modules/puppeteer-core/lib/esm/puppeteer/web.js +21 -21
  581. data/node_modules/puppeteer-core/lib/esm/vendor/mitt/src/index.d.ts +27 -27
  582. data/node_modules/puppeteer-core/lib/esm/vendor/mitt/src/index.js +53 -53
  583. data/node_modules/puppeteer-core/lib/types.d.ts +67 -25
  584. data/node_modules/puppeteer-core/package.json +115 -115
  585. data/node_modules/puppeteer-core/typescript-if-required.js +61 -61
  586. data/node_modules/readable-stream/CONTRIBUTING.md +38 -38
  587. data/node_modules/readable-stream/GOVERNANCE.md +136 -136
  588. data/node_modules/readable-stream/LICENSE +47 -47
  589. data/node_modules/readable-stream/README.md +106 -106
  590. data/node_modules/readable-stream/errors-browser.js +127 -127
  591. data/node_modules/readable-stream/errors.js +116 -116
  592. data/node_modules/readable-stream/experimentalWarning.js +17 -17
  593. data/node_modules/readable-stream/lib/_stream_duplex.js +138 -138
  594. data/node_modules/readable-stream/lib/_stream_passthrough.js +38 -38
  595. data/node_modules/readable-stream/lib/_stream_readable.js +1123 -1123
  596. data/node_modules/readable-stream/lib/_stream_transform.js +200 -200
  597. data/node_modules/readable-stream/lib/_stream_writable.js +696 -696
  598. data/node_modules/readable-stream/lib/internal/streams/async_iterator.js +206 -206
  599. data/node_modules/readable-stream/lib/internal/streams/buffer_list.js +209 -209
  600. data/node_modules/readable-stream/lib/internal/streams/destroy.js +104 -104
  601. data/node_modules/readable-stream/lib/internal/streams/end-of-stream.js +103 -103
  602. data/node_modules/readable-stream/lib/internal/streams/from-browser.js +3 -3
  603. data/node_modules/readable-stream/lib/internal/streams/from.js +63 -63
  604. data/node_modules/readable-stream/lib/internal/streams/pipeline.js +96 -96
  605. data/node_modules/readable-stream/lib/internal/streams/state.js +26 -26
  606. data/node_modules/readable-stream/lib/internal/streams/stream-browser.js +1 -1
  607. data/node_modules/readable-stream/lib/internal/streams/stream.js +1 -1
  608. data/node_modules/readable-stream/package.json +68 -68
  609. data/node_modules/readable-stream/readable-browser.js +9 -9
  610. data/node_modules/readable-stream/readable.js +16 -16
  611. data/node_modules/rimraf/CHANGELOG.md +65 -65
  612. data/node_modules/rimraf/LICENSE +15 -15
  613. data/node_modules/rimraf/README.md +101 -101
  614. data/node_modules/rimraf/bin.js +68 -68
  615. data/node_modules/rimraf/package.json +32 -32
  616. data/node_modules/rimraf/rimraf.js +360 -360
  617. data/node_modules/safe-buffer/LICENSE +21 -21
  618. data/node_modules/safe-buffer/README.md +584 -584
  619. data/node_modules/safe-buffer/index.d.ts +186 -186
  620. data/node_modules/safe-buffer/index.js +65 -65
  621. data/node_modules/safe-buffer/package.json +51 -51
  622. data/node_modules/string_decoder/LICENSE +48 -48
  623. data/node_modules/string_decoder/README.md +47 -47
  624. data/node_modules/string_decoder/lib/string_decoder.js +295 -295
  625. data/node_modules/string_decoder/package.json +34 -34
  626. data/node_modules/tar-fs/.travis.yml +6 -6
  627. data/node_modules/tar-fs/LICENSE +20 -20
  628. data/node_modules/tar-fs/README.md +165 -165
  629. data/node_modules/tar-fs/index.js +351 -351
  630. data/node_modules/tar-fs/package.json +41 -41
  631. data/node_modules/tar-fs/test/fixtures/a/hello.txt +1 -1
  632. data/node_modules/tar-fs/test/fixtures/b/a/test.txt +1 -1
  633. data/node_modules/tar-fs/test/index.js +346 -346
  634. data/node_modules/tar-stream/LICENSE +20 -20
  635. data/node_modules/tar-stream/README.md +168 -168
  636. data/node_modules/tar-stream/extract.js +257 -257
  637. data/node_modules/tar-stream/headers.js +295 -295
  638. data/node_modules/tar-stream/index.js +2 -2
  639. data/node_modules/tar-stream/pack.js +255 -255
  640. data/node_modules/tar-stream/package.json +58 -58
  641. data/node_modules/tar-stream/sandbox.js +11 -11
  642. data/node_modules/through/.travis.yml +5 -5
  643. data/node_modules/through/LICENSE.APACHE2 +15 -15
  644. data/node_modules/through/LICENSE.MIT +24 -24
  645. data/node_modules/through/index.js +108 -108
  646. data/node_modules/through/package.json +36 -36
  647. data/node_modules/through/readme.markdown +64 -64
  648. data/node_modules/through/test/async.js +28 -28
  649. data/node_modules/through/test/auto-destroy.js +30 -30
  650. data/node_modules/through/test/buffering.js +71 -71
  651. data/node_modules/through/test/end.js +45 -45
  652. data/node_modules/through/test/index.js +133 -133
  653. data/node_modules/tr46/.npmignore +4 -4
  654. data/node_modules/tr46/index.js +193 -193
  655. data/node_modules/tr46/package.json +31 -31
  656. data/node_modules/unbzip2-stream/LICENSE +24 -24
  657. data/node_modules/unbzip2-stream/README.md +59 -59
  658. data/node_modules/unbzip2-stream/dist/unbzip2-stream.min.js +1 -1
  659. data/node_modules/unbzip2-stream/index.js +93 -93
  660. data/node_modules/unbzip2-stream/lib/bit_iterator.js +39 -39
  661. data/node_modules/unbzip2-stream/lib/bzip2.js +365 -365
  662. data/node_modules/unbzip2-stream/package.json +51 -51
  663. data/node_modules/util-deprecate/History.md +16 -16
  664. data/node_modules/util-deprecate/LICENSE +24 -24
  665. data/node_modules/util-deprecate/README.md +53 -53
  666. data/node_modules/util-deprecate/browser.js +67 -67
  667. data/node_modules/util-deprecate/node.js +6 -6
  668. data/node_modules/util-deprecate/package.json +27 -27
  669. data/node_modules/webidl-conversions/LICENSE.md +12 -12
  670. data/node_modules/webidl-conversions/README.md +53 -53
  671. data/node_modules/webidl-conversions/lib/index.js +189 -189
  672. data/node_modules/webidl-conversions/package.json +23 -23
  673. data/node_modules/whatwg-url/LICENSE.txt +21 -21
  674. data/node_modules/whatwg-url/README.md +67 -67
  675. data/node_modules/whatwg-url/lib/URL-impl.js +200 -200
  676. data/node_modules/whatwg-url/lib/URL.js +196 -196
  677. data/node_modules/whatwg-url/lib/public-api.js +11 -11
  678. data/node_modules/whatwg-url/lib/utils.js +20 -20
  679. data/node_modules/whatwg-url/package.json +32 -32
  680. data/node_modules/wrappy/LICENSE +15 -15
  681. data/node_modules/wrappy/README.md +36 -36
  682. data/node_modules/wrappy/package.json +29 -29
  683. data/node_modules/wrappy/wrappy.js +33 -33
  684. data/node_modules/ws/LICENSE +19 -19
  685. data/node_modules/ws/README.md +493 -493
  686. data/node_modules/ws/browser.js +8 -8
  687. data/node_modules/ws/index.js +13 -13
  688. data/node_modules/ws/lib/buffer-util.js +126 -126
  689. data/node_modules/ws/lib/constants.js +12 -12
  690. data/node_modules/ws/lib/event-target.js +266 -266
  691. data/node_modules/ws/lib/extension.js +203 -203
  692. data/node_modules/ws/lib/limiter.js +55 -55
  693. data/node_modules/ws/lib/permessage-deflate.js +511 -511
  694. data/node_modules/ws/lib/receiver.js +612 -612
  695. data/node_modules/ws/lib/sender.js +422 -422
  696. data/node_modules/ws/lib/stream.js +180 -180
  697. data/node_modules/ws/lib/subprotocol.js +62 -62
  698. data/node_modules/ws/lib/validation.js +124 -124
  699. data/node_modules/ws/lib/websocket-server.js +485 -485
  700. data/node_modules/ws/lib/websocket.js +1149 -1149
  701. data/node_modules/ws/package.json +61 -61
  702. data/node_modules/ws/wrapper.mjs +8 -8
  703. data/node_modules/yauzl/LICENSE +21 -21
  704. data/node_modules/yauzl/README.md +658 -658
  705. data/node_modules/yauzl/index.js +796 -796
  706. data/node_modules/yauzl/package.json +40 -40
  707. data/package.json +1 -1
  708. metadata +23 -25
  709. data/node_modules/devtools-protocol/changelog.md +0 -10491
  710. data/node_modules/devtools-protocol/externs/protocol_externs.js +0 -9734
@@ -1,2530 +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, 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
- }
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
+ }
2530
2530
  //# sourceMappingURL=Page.js.map