Page.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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. const fs = require('fs');
  17. const EventEmitter = require('events');
  18. const mime = require('mime');
  19. const {Events} = require('./Events');
  20. const {Connection} = require('./Connection');
  21. const {Dialog} = require('./Dialog');
  22. const {EmulationManager} = require('./EmulationManager');
  23. const {FrameManager} = require('./FrameManager');
  24. const {Keyboard, Mouse, Touchscreen} = require('./Input');
  25. const Tracing = require('./Tracing');
  26. const {helper, debugError, assert} = require('./helper');
  27. const {Coverage} = require('./Coverage');
  28. const {Worker} = require('./Worker');
  29. const {createJSHandle} = require('./JSHandle');
  30. const {Accessibility} = require('./Accessibility');
  31. const {TimeoutSettings} = require('./TimeoutSettings');
  32. const writeFileAsync = helper.promisify(fs.writeFile);
  33. class Page extends EventEmitter {
  34. /**
  35. * @param {!Puppeteer.CDPSession} client
  36. * @param {!Puppeteer.Target} target
  37. * @param {boolean} ignoreHTTPSErrors
  38. * @param {?Puppeteer.Viewport} defaultViewport
  39. * @param {!Puppeteer.TaskQueue} screenshotTaskQueue
  40. * @return {!Promise<!Page>}
  41. */
  42. static async create(client, target, ignoreHTTPSErrors, defaultViewport, screenshotTaskQueue) {
  43. const page = new Page(client, target, ignoreHTTPSErrors, screenshotTaskQueue);
  44. await page._initialize();
  45. if (defaultViewport)
  46. await page.setViewport(defaultViewport);
  47. return page;
  48. }
  49. /**
  50. * @param {!Puppeteer.CDPSession} client
  51. * @param {!Puppeteer.Target} target
  52. * @param {boolean} ignoreHTTPSErrors
  53. * @param {!Puppeteer.TaskQueue} screenshotTaskQueue
  54. */
  55. constructor(client, target, ignoreHTTPSErrors, screenshotTaskQueue) {
  56. super();
  57. this._closed = false;
  58. this._client = client;
  59. this._target = target;
  60. this._keyboard = new Keyboard(client);
  61. this._mouse = new Mouse(client, this._keyboard);
  62. this._timeoutSettings = new TimeoutSettings();
  63. this._touchscreen = new Touchscreen(client, this._keyboard);
  64. this._accessibility = new Accessibility(client);
  65. /** @type {!FrameManager} */
  66. this._frameManager = new FrameManager(client, this, ignoreHTTPSErrors, this._timeoutSettings);
  67. this._emulationManager = new EmulationManager(client);
  68. this._tracing = new Tracing(client);
  69. /** @type {!Map<string, Function>} */
  70. this._pageBindings = new Map();
  71. this._coverage = new Coverage(client);
  72. this._javascriptEnabled = true;
  73. /** @type {?Puppeteer.Viewport} */
  74. this._viewport = null;
  75. this._screenshotTaskQueue = screenshotTaskQueue;
  76. /** @type {!Map<string, Worker>} */
  77. this._workers = new Map();
  78. client.on('Target.attachedToTarget', event => {
  79. if (event.targetInfo.type !== 'worker') {
  80. // If we don't detach from service workers, they will never die.
  81. client.send('Target.detachFromTarget', {
  82. sessionId: event.sessionId
  83. }).catch(debugError);
  84. return;
  85. }
  86. const session = Connection.fromSession(client).session(event.sessionId);
  87. const worker = new Worker(session, event.targetInfo.url, this._addConsoleMessage.bind(this), this._handleException.bind(this));
  88. this._workers.set(event.sessionId, worker);
  89. this.emit(Events.Page.WorkerCreated, worker);
  90. });
  91. client.on('Target.detachedFromTarget', event => {
  92. const worker = this._workers.get(event.sessionId);
  93. if (!worker)
  94. return;
  95. this.emit(Events.Page.WorkerDestroyed, worker);
  96. this._workers.delete(event.sessionId);
  97. });
  98. this._frameManager.on(Events.FrameManager.FrameAttached, event => this.emit(Events.Page.FrameAttached, event));
  99. this._frameManager.on(Events.FrameManager.FrameDetached, event => this.emit(Events.Page.FrameDetached, event));
  100. this._frameManager.on(Events.FrameManager.FrameNavigated, event => this.emit(Events.Page.FrameNavigated, event));
  101. const networkManager = this._frameManager.networkManager();
  102. networkManager.on(Events.NetworkManager.Request, event => this.emit(Events.Page.Request, event));
  103. networkManager.on(Events.NetworkManager.Response, event => this.emit(Events.Page.Response, event));
  104. networkManager.on(Events.NetworkManager.RequestFailed, event => this.emit(Events.Page.RequestFailed, event));
  105. networkManager.on(Events.NetworkManager.RequestFinished, event => this.emit(Events.Page.RequestFinished, event));
  106. this._fileChooserInterceptors = new Set();
  107. client.on('Page.domContentEventFired', event => this.emit(Events.Page.DOMContentLoaded));
  108. client.on('Page.loadEventFired', event => this.emit(Events.Page.Load));
  109. client.on('Runtime.consoleAPICalled', event => this._onConsoleAPI(event));
  110. client.on('Runtime.bindingCalled', event => this._onBindingCalled(event));
  111. client.on('Page.javascriptDialogOpening', event => this._onDialog(event));
  112. client.on('Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails));
  113. client.on('Inspector.targetCrashed', event => this._onTargetCrashed());
  114. client.on('Performance.metrics', event => this._emitMetrics(event));
  115. client.on('Log.entryAdded', event => this._onLogEntryAdded(event));
  116. client.on('Page.fileChooserOpened', event => this._onFileChooser(event));
  117. this._target._isClosedPromise.then(() => {
  118. this.emit(Events.Page.Close);
  119. this._closed = true;
  120. });
  121. }
  122. async _initialize() {
  123. await Promise.all([
  124. this._frameManager.initialize(),
  125. this._client.send('Target.setAutoAttach', {autoAttach: true, waitForDebuggerOnStart: false, flatten: true}),
  126. this._client.send('Performance.enable', {}),
  127. this._client.send('Log.enable', {}),
  128. ]);
  129. }
  130. /**
  131. * @param {!Protocol.Page.fileChooserOpenedPayload} event
  132. */
  133. async _onFileChooser(event) {
  134. if (!this._fileChooserInterceptors.size)
  135. return;
  136. const frame = this._frameManager.frame(event.frameId);
  137. const context = await frame.executionContext();
  138. const element = await context._adoptBackendNodeId(event.backendNodeId);
  139. const interceptors = Array.from(this._fileChooserInterceptors);
  140. this._fileChooserInterceptors.clear();
  141. const fileChooser = new FileChooser(this._client, element, event);
  142. for (const interceptor of interceptors)
  143. interceptor.call(null, fileChooser);
  144. }
  145. /**
  146. * @param {!{timeout?: number}=} options
  147. * @return !Promise<!FileChooser>}
  148. */
  149. async waitForFileChooser(options = {}) {
  150. if (!this._fileChooserInterceptors.size)
  151. await this._client.send('Page.setInterceptFileChooserDialog', {enabled: true});
  152. const {
  153. timeout = this._timeoutSettings.timeout(),
  154. } = options;
  155. let callback;
  156. const promise = new Promise(x => callback = x);
  157. this._fileChooserInterceptors.add(callback);
  158. return helper.waitWithTimeout(promise, 'waiting for file chooser', timeout).catch(e => {
  159. this._fileChooserInterceptors.delete(callback);
  160. throw e;
  161. });
  162. }
  163. /**
  164. * @param {!{longitude: number, latitude: number, accuracy: (number|undefined)}} options
  165. */
  166. async setGeolocation(options) {
  167. const { longitude, latitude, accuracy = 0} = options;
  168. if (longitude < -180 || longitude > 180)
  169. throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
  170. if (latitude < -90 || latitude > 90)
  171. throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
  172. if (accuracy < 0)
  173. throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
  174. await this._client.send('Emulation.setGeolocationOverride', {longitude, latitude, accuracy});
  175. }
  176. /**
  177. * @return {!Puppeteer.Target}
  178. */
  179. target() {
  180. return this._target;
  181. }
  182. /**
  183. * @return {!Puppeteer.Browser}
  184. */
  185. browser() {
  186. return this._target.browser();
  187. }
  188. /**
  189. * @return {!Puppeteer.BrowserContext}
  190. */
  191. browserContext() {
  192. return this._target.browserContext();
  193. }
  194. _onTargetCrashed() {
  195. this.emit('error', new Error('Page crashed!'));
  196. }
  197. /**
  198. * @param {!Protocol.Log.entryAddedPayload} event
  199. */
  200. _onLogEntryAdded(event) {
  201. const {level, text, args, source, url, lineNumber} = event.entry;
  202. if (args)
  203. args.map(arg => helper.releaseObject(this._client, arg));
  204. if (source !== 'worker')
  205. this.emit(Events.Page.Console, new ConsoleMessage(level, text, [], {url, lineNumber}));
  206. }
  207. /**
  208. * @return {!Puppeteer.Frame}
  209. */
  210. mainFrame() {
  211. return this._frameManager.mainFrame();
  212. }
  213. /**
  214. * @return {!Keyboard}
  215. */
  216. get keyboard() {
  217. return this._keyboard;
  218. }
  219. /**
  220. * @return {!Touchscreen}
  221. */
  222. get touchscreen() {
  223. return this._touchscreen;
  224. }
  225. /**
  226. * @return {!Coverage}
  227. */
  228. get coverage() {
  229. return this._coverage;
  230. }
  231. /**
  232. * @return {!Tracing}
  233. */
  234. get tracing() {
  235. return this._tracing;
  236. }
  237. /**
  238. * @return {!Accessibility}
  239. */
  240. get accessibility() {
  241. return this._accessibility;
  242. }
  243. /**
  244. * @return {!Array<Puppeteer.Frame>}
  245. */
  246. frames() {
  247. return this._frameManager.frames();
  248. }
  249. /**
  250. * @return {!Array<!Worker>}
  251. */
  252. workers() {
  253. return Array.from(this._workers.values());
  254. }
  255. /**
  256. * @param {boolean} value
  257. */
  258. async setRequestInterception(value) {
  259. return this._frameManager.networkManager().setRequestInterception(value);
  260. }
  261. /**
  262. * @param {boolean} enabled
  263. */
  264. setOfflineMode(enabled) {
  265. return this._frameManager.networkManager().setOfflineMode(enabled);
  266. }
  267. /**
  268. * @param {number} timeout
  269. */
  270. setDefaultNavigationTimeout(timeout) {
  271. this._timeoutSettings.setDefaultNavigationTimeout(timeout);
  272. }
  273. /**
  274. * @param {number} timeout
  275. */
  276. setDefaultTimeout(timeout) {
  277. this._timeoutSettings.setDefaultTimeout(timeout);
  278. }
  279. /**
  280. * @param {string} selector
  281. * @return {!Promise<?Puppeteer.ElementHandle>}
  282. */
  283. async $(selector) {
  284. return this.mainFrame().$(selector);
  285. }
  286. /**
  287. * @param {Function|string} pageFunction
  288. * @param {!Array<*>} args
  289. * @return {!Promise<!Puppeteer.JSHandle>}
  290. */
  291. async evaluateHandle(pageFunction, ...args) {
  292. const context = await this.mainFrame().executionContext();
  293. return context.evaluateHandle(pageFunction, ...args);
  294. }
  295. /**
  296. * @param {!Puppeteer.JSHandle} prototypeHandle
  297. * @return {!Promise<!Puppeteer.JSHandle>}
  298. */
  299. async queryObjects(prototypeHandle) {
  300. const context = await this.mainFrame().executionContext();
  301. return context.queryObjects(prototypeHandle);
  302. }
  303. /**
  304. * @param {string} selector
  305. * @param {Function|string} pageFunction
  306. * @param {!Array<*>} args
  307. * @return {!Promise<(!Object|undefined)>}
  308. */
  309. async $eval(selector, pageFunction, ...args) {
  310. return this.mainFrame().$eval(selector, pageFunction, ...args);
  311. }
  312. /**
  313. * @param {string} selector
  314. * @param {Function|string} pageFunction
  315. * @param {!Array<*>} args
  316. * @return {!Promise<(!Object|undefined)>}
  317. */
  318. async $$eval(selector, pageFunction, ...args) {
  319. return this.mainFrame().$$eval(selector, pageFunction, ...args);
  320. }
  321. /**
  322. * @param {string} selector
  323. * @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
  324. */
  325. async $$(selector) {
  326. return this.mainFrame().$$(selector);
  327. }
  328. /**
  329. * @param {string} expression
  330. * @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
  331. */
  332. async $x(expression) {
  333. return this.mainFrame().$x(expression);
  334. }
  335. /**
  336. * @param {!Array<string>} urls
  337. * @return {!Promise<!Array<Network.Cookie>>}
  338. */
  339. async cookies(...urls) {
  340. return (await this._client.send('Network.getCookies', {
  341. urls: urls.length ? urls : [this.url()]
  342. })).cookies;
  343. }
  344. /**
  345. * @param {Array<Protocol.Network.deleteCookiesParameters>} cookies
  346. */
  347. async deleteCookie(...cookies) {
  348. const pageURL = this.url();
  349. for (const cookie of cookies) {
  350. const item = Object.assign({}, cookie);
  351. if (!cookie.url && pageURL.startsWith('http'))
  352. item.url = pageURL;
  353. await this._client.send('Network.deleteCookies', item);
  354. }
  355. }
  356. /**
  357. * @param {Array<Network.CookieParam>} cookies
  358. */
  359. async setCookie(...cookies) {
  360. const pageURL = this.url();
  361. const startsWithHTTP = pageURL.startsWith('http');
  362. const items = cookies.map(cookie => {
  363. const item = Object.assign({}, cookie);
  364. if (!item.url && startsWithHTTP)
  365. item.url = pageURL;
  366. assert(item.url !== 'about:blank', `Blank page can not have cookie "${item.name}"`);
  367. assert(!String.prototype.startsWith.call(item.url || '', 'data:'), `Data URL page can not have cookie "${item.name}"`);
  368. return item;
  369. });
  370. await this.deleteCookie(...items);
  371. if (items.length)
  372. await this._client.send('Network.setCookies', { cookies: items });
  373. }
  374. /**
  375. * @param {!{url?: string, path?: string, content?: string, type?: string}} options
  376. * @return {!Promise<!Puppeteer.ElementHandle>}
  377. */
  378. async addScriptTag(options) {
  379. return this.mainFrame().addScriptTag(options);
  380. }
  381. /**
  382. * @param {!{url?: string, path?: string, content?: string}} options
  383. * @return {!Promise<!Puppeteer.ElementHandle>}
  384. */
  385. async addStyleTag(options) {
  386. return this.mainFrame().addStyleTag(options);
  387. }
  388. /**
  389. * @param {string} name
  390. * @param {Function} puppeteerFunction
  391. */
  392. async exposeFunction(name, puppeteerFunction) {
  393. if (this._pageBindings.has(name))
  394. throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);
  395. this._pageBindings.set(name, puppeteerFunction);
  396. const expression = helper.evaluationString(addPageBinding, name);
  397. await this._client.send('Runtime.addBinding', {name: name});
  398. await this._client.send('Page.addScriptToEvaluateOnNewDocument', {source: expression});
  399. await Promise.all(this.frames().map(frame => frame.evaluate(expression).catch(debugError)));
  400. function addPageBinding(bindingName) {
  401. const binding = window[bindingName];
  402. window[bindingName] = (...args) => {
  403. const me = window[bindingName];
  404. let callbacks = me['callbacks'];
  405. if (!callbacks) {
  406. callbacks = new Map();
  407. me['callbacks'] = callbacks;
  408. }
  409. const seq = (me['lastSeq'] || 0) + 1;
  410. me['lastSeq'] = seq;
  411. const promise = new Promise((resolve, reject) => callbacks.set(seq, {resolve, reject}));
  412. binding(JSON.stringify({name: bindingName, seq, args}));
  413. return promise;
  414. };
  415. }
  416. }
  417. /**
  418. * @param {?{username: string, password: string}} credentials
  419. */
  420. async authenticate(credentials) {
  421. return this._frameManager.networkManager().authenticate(credentials);
  422. }
  423. /**
  424. * @param {!Object<string, string>} headers
  425. */
  426. async setExtraHTTPHeaders(headers) {
  427. return this._frameManager.networkManager().setExtraHTTPHeaders(headers);
  428. }
  429. /**
  430. * @param {string} userAgent
  431. */
  432. async setUserAgent(userAgent) {
  433. return this._frameManager.networkManager().setUserAgent(userAgent);
  434. }
  435. /**
  436. * @return {!Promise<!Metrics>}
  437. */
  438. async metrics() {
  439. const response = await this._client.send('Performance.getMetrics');
  440. return this._buildMetricsObject(response.metrics);
  441. }
  442. /**
  443. * @param {!Protocol.Performance.metricsPayload} event
  444. */
  445. _emitMetrics(event) {
  446. this.emit(Events.Page.Metrics, {
  447. title: event.title,
  448. metrics: this._buildMetricsObject(event.metrics)
  449. });
  450. }
  451. /**
  452. * @param {?Array<!Protocol.Performance.Metric>} metrics
  453. * @return {!Metrics}
  454. */
  455. _buildMetricsObject(metrics) {
  456. const result = {};
  457. for (const metric of metrics || []) {
  458. if (supportedMetrics.has(metric.name))
  459. result[metric.name] = metric.value;
  460. }
  461. return result;
  462. }
  463. /**
  464. * @param {!Protocol.Runtime.ExceptionDetails} exceptionDetails
  465. */
  466. _handleException(exceptionDetails) {
  467. const message = helper.getExceptionMessage(exceptionDetails);
  468. const err = new Error(message);
  469. err.stack = ''; // Don't report clientside error with a node stack attached
  470. this.emit(Events.Page.PageError, err);
  471. }
  472. /**
  473. * @param {!Protocol.Runtime.consoleAPICalledPayload} event
  474. */
  475. async _onConsoleAPI(event) {
  476. if (event.executionContextId === 0) {
  477. // DevTools protocol stores the last 1000 console messages. These
  478. // messages are always reported even for removed execution contexts. In
  479. // this case, they are marked with executionContextId = 0 and are
  480. // reported upon enabling Runtime agent.
  481. //
  482. // Ignore these messages since:
  483. // - there's no execution context we can use to operate with message
  484. // arguments
  485. // - these messages are reported before Puppeteer clients can subscribe
  486. // to the 'console'
  487. // page event.
  488. //
  489. // @see https://github.com/puppeteer/puppeteer/issues/3865
  490. return;
  491. }
  492. const context = this._frameManager.executionContextById(event.executionContextId);
  493. const values = event.args.map(arg => createJSHandle(context, arg));
  494. this._addConsoleMessage(event.type, values, event.stackTrace);
  495. }
  496. /**
  497. * @param {!Protocol.Runtime.bindingCalledPayload} event
  498. */
  499. async _onBindingCalled(event) {
  500. const {name, seq, args} = JSON.parse(event.payload);
  501. let expression = null;
  502. try {
  503. const result = await this._pageBindings.get(name)(...args);
  504. expression = helper.evaluationString(deliverResult, name, seq, result);
  505. } catch (error) {
  506. if (error instanceof Error)
  507. expression = helper.evaluationString(deliverError, name, seq, error.message, error.stack);
  508. else
  509. expression = helper.evaluationString(deliverErrorValue, name, seq, error);
  510. }
  511. this._client.send('Runtime.evaluate', { expression, contextId: event.executionContextId }).catch(debugError);
  512. /**
  513. * @param {string} name
  514. * @param {number} seq
  515. * @param {*} result
  516. */
  517. function deliverResult(name, seq, result) {
  518. window[name]['callbacks'].get(seq).resolve(result);
  519. window[name]['callbacks'].delete(seq);
  520. }
  521. /**
  522. * @param {string} name
  523. * @param {number} seq
  524. * @param {string} message
  525. * @param {string} stack
  526. */
  527. function deliverError(name, seq, message, stack) {
  528. const error = new Error(message);
  529. error.stack = stack;
  530. window[name]['callbacks'].get(seq).reject(error);
  531. window[name]['callbacks'].delete(seq);
  532. }
  533. /**
  534. * @param {string} name
  535. * @param {number} seq
  536. * @param {*} value
  537. */
  538. function deliverErrorValue(name, seq, value) {
  539. window[name]['callbacks'].get(seq).reject(value);
  540. window[name]['callbacks'].delete(seq);
  541. }
  542. }
  543. /**
  544. * @param {string} type
  545. * @param {!Array<!Puppeteer.JSHandle>} args
  546. * @param {Protocol.Runtime.StackTrace=} stackTrace
  547. */
  548. _addConsoleMessage(type, args, stackTrace) {
  549. if (!this.listenerCount(Events.Page.Console)) {
  550. args.forEach(arg => arg.dispose());
  551. return;
  552. }
  553. const textTokens = [];
  554. for (const arg of args) {
  555. const remoteObject = arg._remoteObject;
  556. if (remoteObject.objectId)
  557. textTokens.push(arg.toString());
  558. else
  559. textTokens.push(helper.valueFromRemoteObject(remoteObject));
  560. }
  561. const location = stackTrace && stackTrace.callFrames.length ? {
  562. url: stackTrace.callFrames[0].url,
  563. lineNumber: stackTrace.callFrames[0].lineNumber,
  564. columnNumber: stackTrace.callFrames[0].columnNumber,
  565. } : {};
  566. const message = new ConsoleMessage(type, textTokens.join(' '), args, location);
  567. this.emit(Events.Page.Console, message);
  568. }
  569. _onDialog(event) {
  570. let dialogType = null;
  571. if (event.type === 'alert')
  572. dialogType = Dialog.Type.Alert;
  573. else if (event.type === 'confirm')
  574. dialogType = Dialog.Type.Confirm;
  575. else if (event.type === 'prompt')
  576. dialogType = Dialog.Type.Prompt;
  577. else if (event.type === 'beforeunload')
  578. dialogType = Dialog.Type.BeforeUnload;
  579. assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
  580. const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt);
  581. this.emit(Events.Page.Dialog, dialog);
  582. }
  583. /**
  584. * @return {!string}
  585. */
  586. url() {
  587. return this.mainFrame().url();
  588. }
  589. /**
  590. * @return {!Promise<string>}
  591. */
  592. async content() {
  593. return await this._frameManager.mainFrame().content();
  594. }
  595. /**
  596. * @param {string} html
  597. * @param {!{timeout?: number, waitUntil?: string|!Array<string>}=} options
  598. */
  599. async setContent(html, options) {
  600. await this._frameManager.mainFrame().setContent(html, options);
  601. }
  602. /**
  603. * @param {string} url
  604. * @param {!{referer?: string, timeout?: number, waitUntil?: string|!Array<string>}=} options
  605. * @return {!Promise<?Puppeteer.Response>}
  606. */
  607. async goto(url, options) {
  608. return await this._frameManager.mainFrame().goto(url, options);
  609. }
  610. /**
  611. * @param {!{timeout?: number, waitUntil?: string|!Array<string>}=} options
  612. * @return {!Promise<?Puppeteer.Response>}
  613. */
  614. async reload(options) {
  615. const [response] = await Promise.all([
  616. this.waitForNavigation(options),
  617. this._client.send('Page.reload')
  618. ]);
  619. return response;
  620. }
  621. /**
  622. * @param {!{timeout?: number, waitUntil?: string|!Array<string>}=} options
  623. * @return {!Promise<?Puppeteer.Response>}
  624. */
  625. async waitForNavigation(options = {}) {
  626. return await this._frameManager.mainFrame().waitForNavigation(options);
  627. }
  628. _sessionClosePromise() {
  629. if (!this._disconnectPromise)
  630. this._disconnectPromise = new Promise(fulfill => this._client.once(Events.CDPSession.Disconnected, () => fulfill(new Error('Target closed'))));
  631. return this._disconnectPromise;
  632. }
  633. /**
  634. * @param {(string|Function)} urlOrPredicate
  635. * @param {!{timeout?: number}=} options
  636. * @return {!Promise<!Puppeteer.Request>}
  637. */
  638. async waitForRequest(urlOrPredicate, options = {}) {
  639. const {
  640. timeout = this._timeoutSettings.timeout(),
  641. } = options;
  642. return helper.waitForEvent(this._frameManager.networkManager(), Events.NetworkManager.Request, request => {
  643. if (helper.isString(urlOrPredicate))
  644. return (urlOrPredicate === request.url());
  645. if (typeof urlOrPredicate === 'function')
  646. return !!(urlOrPredicate(request));
  647. return false;
  648. }, timeout, this._sessionClosePromise());
  649. }
  650. /**
  651. * @param {(string|Function)} urlOrPredicate
  652. * @param {!{timeout?: number}=} options
  653. * @return {!Promise<!Puppeteer.Response>}
  654. */
  655. async waitForResponse(urlOrPredicate, options = {}) {
  656. const {
  657. timeout = this._timeoutSettings.timeout(),
  658. } = options;
  659. return helper.waitForEvent(this._frameManager.networkManager(), Events.NetworkManager.Response, response => {
  660. if (helper.isString(urlOrPredicate))
  661. return (urlOrPredicate === response.url());
  662. if (typeof urlOrPredicate === 'function')
  663. return !!(urlOrPredicate(response));
  664. return false;
  665. }, timeout, this._sessionClosePromise());
  666. }
  667. /**
  668. * @param {!{timeout?: number, waitUntil?: string|!Array<string>}=} options
  669. * @return {!Promise<?Puppeteer.Response>}
  670. */
  671. async goBack(options) {
  672. return this._go(-1, options);
  673. }
  674. /**
  675. * @param {!{timeout?: number, waitUntil?: string|!Array<string>}=} options
  676. * @return {!Promise<?Puppeteer.Response>}
  677. */
  678. async goForward(options) {
  679. return this._go(+1, options);
  680. }
  681. /**
  682. * @param {!{timeout?: number, waitUntil?: string|!Array<string>}=} options
  683. * @return {!Promise<?Puppeteer.Response>}
  684. */
  685. async _go(delta, options) {
  686. const history = await this._client.send('Page.getNavigationHistory');
  687. const entry = history.entries[history.currentIndex + delta];
  688. if (!entry)
  689. return null;
  690. const [response] = await Promise.all([
  691. this.waitForNavigation(options),
  692. this._client.send('Page.navigateToHistoryEntry', {entryId: entry.id}),
  693. ]);
  694. return response;
  695. }
  696. async bringToFront() {
  697. await this._client.send('Page.bringToFront');
  698. }
  699. /**
  700. * @param {!{viewport: !Puppeteer.Viewport, userAgent: string}} options
  701. */
  702. async emulate(options) {
  703. await Promise.all([
  704. this.setViewport(options.viewport),
  705. this.setUserAgent(options.userAgent)
  706. ]);
  707. }
  708. /**
  709. * @param {boolean} enabled
  710. */
  711. async setJavaScriptEnabled(enabled) {
  712. if (this._javascriptEnabled === enabled)
  713. return;
  714. this._javascriptEnabled = enabled;
  715. await this._client.send('Emulation.setScriptExecutionDisabled', { value: !enabled });
  716. }
  717. /**
  718. * @param {boolean} enabled
  719. */
  720. async setBypassCSP(enabled) {
  721. await this._client.send('Page.setBypassCSP', { enabled });
  722. }
  723. /**
  724. * @param {?string} type
  725. */
  726. async emulateMediaType(type) {
  727. assert(type === 'screen' || type === 'print' || type === null, 'Unsupported media type: ' + type);
  728. await this._client.send('Emulation.setEmulatedMedia', {media: type || ''});
  729. }
  730. /**
  731. * @param {?Array<MediaFeature>} features
  732. */
  733. async emulateMediaFeatures(features) {
  734. if (features === null)
  735. await this._client.send('Emulation.setEmulatedMedia', {features: null});
  736. if (Array.isArray(features)) {
  737. features.every(mediaFeature => {
  738. const name = mediaFeature.name;
  739. assert(/^prefers-(?:color-scheme|reduced-motion)$/.test(name), 'Unsupported media feature: ' + name);
  740. return true;
  741. });
  742. await this._client.send('Emulation.setEmulatedMedia', {features: features});
  743. }
  744. }
  745. /**
  746. * @param {?string} timezoneId
  747. */
  748. async emulateTimezone(timezoneId) {
  749. try {
  750. await this._client.send('Emulation.setTimezoneOverride', {timezoneId: timezoneId || ''});
  751. } catch (exception) {
  752. if (exception.message.includes('Invalid timezone'))
  753. throw new Error(`Invalid timezone ID: ${timezoneId}`);
  754. throw exception;
  755. }
  756. }
  757. /**
  758. * @param {!Puppeteer.Viewport} viewport
  759. */
  760. async setViewport(viewport) {
  761. const needsReload = await this._emulationManager.emulateViewport(viewport);
  762. this._viewport = viewport;
  763. if (needsReload)
  764. await this.reload();
  765. }
  766. /**
  767. * @return {?Puppeteer.Viewport}
  768. */
  769. viewport() {
  770. return this._viewport;
  771. }
  772. /**
  773. * @param {Function|string} pageFunction
  774. * @param {!Array<*>} args
  775. * @return {!Promise<*>}
  776. */
  777. async evaluate(pageFunction, ...args) {
  778. return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
  779. }
  780. /**
  781. * @param {Function|string} pageFunction
  782. * @param {!Array<*>} args
  783. */
  784. async evaluateOnNewDocument(pageFunction, ...args) {
  785. const source = helper.evaluationString(pageFunction, ...args);
  786. await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source });
  787. }
  788. /**
  789. * @param {boolean} enabled
  790. */
  791. async setCacheEnabled(enabled = true) {
  792. await this._frameManager.networkManager().setCacheEnabled(enabled);
  793. }
  794. /**
  795. * @param {!ScreenshotOptions=} options
  796. * @return {!Promise<!Buffer|!String>}
  797. */
  798. async screenshot(options = {}) {
  799. let screenshotType = null;
  800. // options.type takes precedence over inferring the type from options.path
  801. // because it may be a 0-length file with no extension created beforehand (i.e. as a temp file).
  802. if (options.type) {
  803. assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type);
  804. screenshotType = options.type;
  805. } else if (options.path) {
  806. const mimeType = mime.getType(options.path);
  807. if (mimeType === 'image/png')
  808. screenshotType = 'png';
  809. else if (mimeType === 'image/jpeg')
  810. screenshotType = 'jpeg';
  811. assert(screenshotType, 'Unsupported screenshot mime type: ' + mimeType);
  812. }
  813. if (!screenshotType)
  814. screenshotType = 'png';
  815. if (options.quality) {
  816. assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' + screenshotType + ' screenshots');
  817. assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' + (typeof options.quality));
  818. assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');
  819. assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' + options.quality);
  820. }
  821. assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');
  822. if (options.clip) {
  823. assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x));
  824. assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y));
  825. assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width));
  826. assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height));
  827. assert(options.clip.width !== 0, 'Expected options.clip.width not to be 0.');
  828. assert(options.clip.height !== 0, 'Expected options.clip.height not to be 0.');
  829. }
  830. return this._screenshotTaskQueue.postTask(this._screenshotTask.bind(this, screenshotType, options));
  831. }
  832. /**
  833. * @param {"png"|"jpeg"} format
  834. * @param {!ScreenshotOptions=} options
  835. * @return {!Promise<!Buffer|!String>}
  836. */
  837. async _screenshotTask(format, options) {
  838. await this._client.send('Target.activateTarget', {targetId: this._target._targetId});
  839. let clip = options.clip ? processClip(options.clip) : undefined;
  840. if (options.fullPage) {
  841. const metrics = await this._client.send('Page.getLayoutMetrics');
  842. const width = Math.ceil(metrics.contentSize.width);
  843. const height = Math.ceil(metrics.contentSize.height);
  844. // Overwrite clip for full page at all times.
  845. clip = { x: 0, y: 0, width, height, scale: 1 };
  846. const {
  847. isMobile = false,
  848. deviceScaleFactor = 1,
  849. isLandscape = false
  850. } = this._viewport || {};
  851. /** @type {!Protocol.Emulation.ScreenOrientation} */
  852. const screenOrientation = isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
  853. await this._client.send('Emulation.setDeviceMetricsOverride', { mobile: isMobile, width, height, deviceScaleFactor, screenOrientation });
  854. }
  855. const shouldSetDefaultBackground = options.omitBackground && format === 'png';
  856. if (shouldSetDefaultBackground)
  857. await this._client.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
  858. const result = await this._client.send('Page.captureScreenshot', { format, quality: options.quality, clip });
  859. if (shouldSetDefaultBackground)
  860. await this._client.send('Emulation.setDefaultBackgroundColorOverride');
  861. if (options.fullPage && this._viewport)
  862. await this.setViewport(this._viewport);
  863. const buffer = options.encoding === 'base64' ? result.data : Buffer.from(result.data, 'base64');
  864. if (options.path)
  865. await writeFileAsync(options.path, buffer);
  866. return buffer;
  867. function processClip(clip) {
  868. const x = Math.round(clip.x);
  869. const y = Math.round(clip.y);
  870. const width = Math.round(clip.width + clip.x - x);
  871. const height = Math.round(clip.height + clip.y - y);
  872. return {x, y, width, height, scale: 1};
  873. }
  874. }
  875. /**
  876. * @param {!PDFOptions=} options
  877. * @return {!Promise<!Buffer>}
  878. */
  879. async pdf(options = {}) {
  880. const {
  881. scale = 1,
  882. displayHeaderFooter = false,
  883. headerTemplate = '',
  884. footerTemplate = '',
  885. printBackground = false,
  886. landscape = false,
  887. pageRanges = '',
  888. preferCSSPageSize = false,
  889. margin = {},
  890. path = null
  891. } = options;
  892. let paperWidth = 8.5;
  893. let paperHeight = 11;
  894. if (options.format) {
  895. const format = Page.PaperFormats[options.format.toLowerCase()];
  896. assert(format, 'Unknown paper format: ' + options.format);
  897. paperWidth = format.width;
  898. paperHeight = format.height;
  899. } else {
  900. paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
  901. paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
  902. }
  903. const marginTop = convertPrintParameterToInches(margin.top) || 0;
  904. const marginLeft = convertPrintParameterToInches(margin.left) || 0;
  905. const marginBottom = convertPrintParameterToInches(margin.bottom) || 0;
  906. const marginRight = convertPrintParameterToInches(margin.right) || 0;
  907. const result = await this._client.send('Page.printToPDF', {
  908. transferMode: 'ReturnAsStream',
  909. landscape,
  910. displayHeaderFooter,
  911. headerTemplate,
  912. footerTemplate,
  913. printBackground,
  914. scale,
  915. paperWidth,
  916. paperHeight,
  917. marginTop,
  918. marginBottom,
  919. marginLeft,
  920. marginRight,
  921. pageRanges,
  922. preferCSSPageSize
  923. });
  924. return await helper.readProtocolStream(this._client, result.stream, path);
  925. }
  926. /**
  927. * @return {!Promise<string>}
  928. */
  929. async title() {
  930. return this.mainFrame().title();
  931. }
  932. /**
  933. * @param {!{runBeforeUnload: (boolean|undefined)}=} options
  934. */
  935. async close(options = {runBeforeUnload: undefined}) {
  936. assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');
  937. const runBeforeUnload = !!options.runBeforeUnload;
  938. if (runBeforeUnload) {
  939. await this._client.send('Page.close');
  940. } else {
  941. await this._client._connection.send('Target.closeTarget', { targetId: this._target._targetId });
  942. await this._target._isClosedPromise;
  943. }
  944. }
  945. /**
  946. * @return {boolean}
  947. */
  948. isClosed() {
  949. return this._closed;
  950. }
  951. /**
  952. * @return {!Mouse}
  953. */
  954. get mouse() {
  955. return this._mouse;
  956. }
  957. /**
  958. * @param {string} selector
  959. * @param {!{delay?: number, button?: "left"|"right"|"middle", clickCount?: number}=} options
  960. */
  961. click(selector, options = {}) {
  962. return this.mainFrame().click(selector, options);
  963. }
  964. /**
  965. * @param {string} selector
  966. */
  967. focus(selector) {
  968. return this.mainFrame().focus(selector);
  969. }
  970. /**
  971. * @param {string} selector
  972. */
  973. hover(selector) {
  974. return this.mainFrame().hover(selector);
  975. }
  976. /**
  977. * @param {string} selector
  978. * @param {!Array<string>} values
  979. * @return {!Promise<!Array<string>>}
  980. */
  981. select(selector, ...values) {
  982. return this.mainFrame().select(selector, ...values);
  983. }
  984. /**
  985. * @param {string} selector
  986. */
  987. tap(selector) {
  988. return this.mainFrame().tap(selector);
  989. }
  990. /**
  991. * @param {string} selector
  992. * @param {string} text
  993. * @param {{delay: (number|undefined)}=} options
  994. */
  995. type(selector, text, options) {
  996. return this.mainFrame().type(selector, text, options);
  997. }
  998. /**
  999. * @param {(string|number|Function)} selectorOrFunctionOrTimeout
  1000. * @param {!{visible?: boolean, hidden?: boolean, timeout?: number, polling?: string|number}=} options
  1001. * @param {!Array<*>} args
  1002. * @return {!Promise<!Puppeteer.JSHandle>}
  1003. */
  1004. waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
  1005. return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
  1006. }
  1007. /**
  1008. * @param {string} selector
  1009. * @param {!{visible?: boolean, hidden?: boolean, timeout?: number}=} options
  1010. * @return {!Promise<?Puppeteer.ElementHandle>}
  1011. */
  1012. waitForSelector(selector, options = {}) {
  1013. return this.mainFrame().waitForSelector(selector, options);
  1014. }
  1015. /**
  1016. * @param {string} xpath
  1017. * @param {!{visible?: boolean, hidden?: boolean, timeout?: number}=} options
  1018. * @return {!Promise<?Puppeteer.ElementHandle>}
  1019. */
  1020. waitForXPath(xpath, options = {}) {
  1021. return this.mainFrame().waitForXPath(xpath, options);
  1022. }
  1023. /**
  1024. * @param {Function} pageFunction
  1025. * @param {!{polling?: string|number, timeout?: number}=} options
  1026. * @param {!Array<*>} args
  1027. * @return {!Promise<!Puppeteer.JSHandle>}
  1028. */
  1029. waitForFunction(pageFunction, options = {}, ...args) {
  1030. return this.mainFrame().waitForFunction(pageFunction, options, ...args);
  1031. }
  1032. }
  1033. // Expose alias for deprecated method.
  1034. Page.prototype.emulateMedia = Page.prototype.emulateMediaType;
  1035. /**
  1036. * @typedef {Object} PDFOptions
  1037. * @property {number=} scale
  1038. * @property {boolean=} displayHeaderFooter
  1039. * @property {string=} headerTemplate
  1040. * @property {string=} footerTemplate
  1041. * @property {boolean=} printBackground
  1042. * @property {boolean=} landscape
  1043. * @property {string=} pageRanges
  1044. * @property {string=} format
  1045. * @property {string|number=} width
  1046. * @property {string|number=} height
  1047. * @property {boolean=} preferCSSPageSize
  1048. * @property {!{top?: string|number, bottom?: string|number, left?: string|number, right?: string|number}=} margin
  1049. * @property {string=} path
  1050. */
  1051. /**
  1052. * @typedef {Object} Metrics
  1053. * @property {number=} Timestamp
  1054. * @property {number=} Documents
  1055. * @property {number=} Frames
  1056. * @property {number=} JSEventListeners
  1057. * @property {number=} Nodes
  1058. * @property {number=} LayoutCount
  1059. * @property {number=} RecalcStyleCount
  1060. * @property {number=} LayoutDuration
  1061. * @property {number=} RecalcStyleDuration
  1062. * @property {number=} ScriptDuration
  1063. * @property {number=} TaskDuration
  1064. * @property {number=} JSHeapUsedSize
  1065. * @property {number=} JSHeapTotalSize
  1066. */
  1067. /**
  1068. * @typedef {Object} ScreenshotOptions
  1069. * @property {string=} type
  1070. * @property {string=} path
  1071. * @property {boolean=} fullPage
  1072. * @property {{x: number, y: number, width: number, height: number}=} clip
  1073. * @property {number=} quality
  1074. * @property {boolean=} omitBackground
  1075. * @property {string=} encoding
  1076. */
  1077. /**
  1078. * @typedef {Object} MediaFeature
  1079. * @property {string} name
  1080. * @property {string} value
  1081. */
  1082. /** @type {!Set<string>} */
  1083. const supportedMetrics = new Set([
  1084. 'Timestamp',
  1085. 'Documents',
  1086. 'Frames',
  1087. 'JSEventListeners',
  1088. 'Nodes',
  1089. 'LayoutCount',
  1090. 'RecalcStyleCount',
  1091. 'LayoutDuration',
  1092. 'RecalcStyleDuration',
  1093. 'ScriptDuration',
  1094. 'TaskDuration',
  1095. 'JSHeapUsedSize',
  1096. 'JSHeapTotalSize',
  1097. ]);
  1098. /** @enum {!{width: number, height: number}} */
  1099. Page.PaperFormats = {
  1100. letter: {width: 8.5, height: 11},
  1101. legal: {width: 8.5, height: 14},
  1102. tabloid: {width: 11, height: 17},
  1103. ledger: {width: 17, height: 11},
  1104. a0: {width: 33.1, height: 46.8 },
  1105. a1: {width: 23.4, height: 33.1 },
  1106. a2: {width: 16.54, height: 23.4 },
  1107. a3: {width: 11.7, height: 16.54 },
  1108. a4: {width: 8.27, height: 11.7 },
  1109. a5: {width: 5.83, height: 8.27 },
  1110. a6: {width: 4.13, height: 5.83 },
  1111. };
  1112. const unitToPixels = {
  1113. 'px': 1,
  1114. 'in': 96,
  1115. 'cm': 37.8,
  1116. 'mm': 3.78
  1117. };
  1118. /**
  1119. * @param {(string|number|undefined)} parameter
  1120. * @return {(number|undefined)}
  1121. */
  1122. function convertPrintParameterToInches(parameter) {
  1123. if (typeof parameter === 'undefined')
  1124. return undefined;
  1125. let pixels;
  1126. if (helper.isNumber(parameter)) {
  1127. // Treat numbers as pixel values to be aligned with phantom's paperSize.
  1128. pixels = /** @type {number} */ (parameter);
  1129. } else if (helper.isString(parameter)) {
  1130. const text = /** @type {string} */ (parameter);
  1131. let unit = text.substring(text.length - 2).toLowerCase();
  1132. let valueText = '';
  1133. if (unitToPixels.hasOwnProperty(unit)) {
  1134. valueText = text.substring(0, text.length - 2);
  1135. } else {
  1136. // In case of unknown unit try to parse the whole parameter as number of pixels.
  1137. // This is consistent with phantom's paperSize behavior.
  1138. unit = 'px';
  1139. valueText = text;
  1140. }
  1141. const value = Number(valueText);
  1142. assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
  1143. pixels = value * unitToPixels[unit];
  1144. } else {
  1145. throw new Error('page.pdf() Cannot handle parameter type: ' + (typeof parameter));
  1146. }
  1147. return pixels / 96;
  1148. }
  1149. /**
  1150. * @typedef {Object} Network.Cookie
  1151. * @property {string} name
  1152. * @property {string} value
  1153. * @property {string} domain
  1154. * @property {string} path
  1155. * @property {number} expires
  1156. * @property {number} size
  1157. * @property {boolean} httpOnly
  1158. * @property {boolean} secure
  1159. * @property {boolean} session
  1160. * @property {("Strict"|"Lax"|"Extended"|"None")=} sameSite
  1161. */
  1162. /**
  1163. * @typedef {Object} Network.CookieParam
  1164. * @property {string} name
  1165. * @property {string} value
  1166. * @property {string=} url
  1167. * @property {string=} domain
  1168. * @property {string=} path
  1169. * @property {number=} expires
  1170. * @property {boolean=} httpOnly
  1171. * @property {boolean=} secure
  1172. * @property {("Strict"|"Lax")=} sameSite
  1173. */
  1174. /**
  1175. * @typedef {Object} ConsoleMessage.Location
  1176. * @property {string=} url
  1177. * @property {number=} lineNumber
  1178. * @property {number=} columnNumber
  1179. */
  1180. class ConsoleMessage {
  1181. /**
  1182. * @param {string} type
  1183. * @param {string} text
  1184. * @param {!Array<!Puppeteer.JSHandle>} args
  1185. * @param {ConsoleMessage.Location} location
  1186. */
  1187. constructor(type, text, args, location = {}) {
  1188. this._type = type;
  1189. this._text = text;
  1190. this._args = args;
  1191. this._location = location;
  1192. }
  1193. /**
  1194. * @return {string}
  1195. */
  1196. type() {
  1197. return this._type;
  1198. }
  1199. /**
  1200. * @return {string}
  1201. */
  1202. text() {
  1203. return this._text;
  1204. }
  1205. /**
  1206. * @return {!Array<!Puppeteer.JSHandle>}
  1207. */
  1208. args() {
  1209. return this._args;
  1210. }
  1211. /**
  1212. * @return {Object}
  1213. */
  1214. location() {
  1215. return this._location;
  1216. }
  1217. }
  1218. class FileChooser {
  1219. /**
  1220. * @param {Puppeteer.CDPSession} client
  1221. * @param {Puppeteer.ElementHandle} element
  1222. * @param {!Protocol.Page.fileChooserOpenedPayload} event
  1223. */
  1224. constructor(client, element, event) {
  1225. this._client = client;
  1226. this._element = element;
  1227. this._multiple = event.mode !== 'selectSingle';
  1228. this._handled = false;
  1229. }
  1230. /**
  1231. * @return {boolean}
  1232. */
  1233. isMultiple() {
  1234. return this._multiple;
  1235. }
  1236. /**
  1237. * @param {!Array<string>} filePaths
  1238. * @return {!Promise}
  1239. */
  1240. async accept(filePaths) {
  1241. assert(!this._handled, 'Cannot accept FileChooser which is already handled!');
  1242. this._handled = true;
  1243. await this._element.uploadFile(...filePaths);
  1244. }
  1245. /**
  1246. * @return {!Promise}
  1247. */
  1248. async cancel() {
  1249. assert(!this._handled, 'Cannot cancel FileChooser which is already handled!');
  1250. this._handled = true;
  1251. }
  1252. }
  1253. module.exports = {Page, ConsoleMessage, FileChooser};