page.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.Page = exports.BindingCall = void 0;
  6. var _fs = _interopRequireDefault(require("fs"));
  7. var _path = _interopRequireDefault(require("path"));
  8. var _errors = require("./errors");
  9. var _network = require("../utils/network");
  10. var _timeoutSettings = require("../common/timeoutSettings");
  11. var _utils = require("../utils");
  12. var _fileUtils = require("../utils/fileUtils");
  13. var _accessibility = require("./accessibility");
  14. var _artifact = require("./artifact");
  15. var _channelOwner = require("./channelOwner");
  16. var _clientHelper = require("./clientHelper");
  17. var _coverage = require("./coverage");
  18. var _download = require("./download");
  19. var _elementHandle = require("./elementHandle");
  20. var _events = require("./events");
  21. var _fileChooser = require("./fileChooser");
  22. var _frame = require("./frame");
  23. var _input = require("./input");
  24. var _jsHandle = require("./jsHandle");
  25. var _stringUtils = require("../utils/isomorphic/stringUtils");
  26. var _network2 = require("./network");
  27. var _video = require("./video");
  28. var _waiter = require("./waiter");
  29. var _worker = require("./worker");
  30. var _harRouter = require("./harRouter");
  31. let _Symbol$asyncDispose;
  32. /**
  33. * Copyright 2017 Google Inc. All rights reserved.
  34. * Modifications copyright (c) Microsoft Corporation.
  35. *
  36. * Licensed under the Apache License, Version 2.0 (the "License");
  37. * you may not use this file except in compliance with the License.
  38. * You may obtain a copy of the License at
  39. *
  40. * http://www.apache.org/licenses/LICENSE-2.0
  41. *
  42. * Unless required by applicable law or agreed to in writing, software
  43. * distributed under the License is distributed on an "AS IS" BASIS,
  44. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  45. * See the License for the specific language governing permissions and
  46. * limitations under the License.
  47. */
  48. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  49. _Symbol$asyncDispose = Symbol.asyncDispose;
  50. class Page extends _channelOwner.ChannelOwner {
  51. static from(page) {
  52. return page._object;
  53. }
  54. static fromNullable(page) {
  55. return page ? Page.from(page) : null;
  56. }
  57. constructor(parent, type, guid, initializer) {
  58. super(parent, type, guid, initializer);
  59. this._browserContext = void 0;
  60. this._ownedContext = void 0;
  61. this._mainFrame = void 0;
  62. this._frames = new Set();
  63. this._workers = new Set();
  64. this._closed = false;
  65. this._closedOrCrashedScope = new _utils.LongStandingScope();
  66. this._viewportSize = void 0;
  67. this._routes = [];
  68. this.accessibility = void 0;
  69. this.coverage = void 0;
  70. this.keyboard = void 0;
  71. this.mouse = void 0;
  72. this.request = void 0;
  73. this.touchscreen = void 0;
  74. this._bindings = new Map();
  75. this._timeoutSettings = void 0;
  76. this._video = null;
  77. this._opener = void 0;
  78. this._closeReason = void 0;
  79. this._closeWasCalled = false;
  80. this._harRouters = [];
  81. this._browserContext = parent;
  82. this._timeoutSettings = new _timeoutSettings.TimeoutSettings(this._browserContext._timeoutSettings);
  83. this.accessibility = new _accessibility.Accessibility(this._channel);
  84. this.keyboard = new _input.Keyboard(this);
  85. this.mouse = new _input.Mouse(this);
  86. this.request = this._browserContext.request;
  87. this.touchscreen = new _input.Touchscreen(this);
  88. this._mainFrame = _frame.Frame.from(initializer.mainFrame);
  89. this._mainFrame._page = this;
  90. this._frames.add(this._mainFrame);
  91. this._viewportSize = initializer.viewportSize || null;
  92. this._closed = initializer.isClosed;
  93. this._opener = Page.fromNullable(initializer.opener);
  94. this._channel.on('bindingCall', ({
  95. binding
  96. }) => this._onBinding(BindingCall.from(binding)));
  97. this._channel.on('close', () => this._onClose());
  98. this._channel.on('crash', () => this._onCrash());
  99. this._channel.on('download', ({
  100. url,
  101. suggestedFilename,
  102. artifact
  103. }) => {
  104. const artifactObject = _artifact.Artifact.from(artifact);
  105. this.emit(_events.Events.Page.Download, new _download.Download(this, url, suggestedFilename, artifactObject));
  106. });
  107. this._channel.on('fileChooser', ({
  108. element,
  109. isMultiple
  110. }) => this.emit(_events.Events.Page.FileChooser, new _fileChooser.FileChooser(this, _elementHandle.ElementHandle.from(element), isMultiple)));
  111. this._channel.on('frameAttached', ({
  112. frame
  113. }) => this._onFrameAttached(_frame.Frame.from(frame)));
  114. this._channel.on('frameDetached', ({
  115. frame
  116. }) => this._onFrameDetached(_frame.Frame.from(frame)));
  117. this._channel.on('route', ({
  118. route
  119. }) => this._onRoute(_network2.Route.from(route)));
  120. this._channel.on('video', ({
  121. artifact
  122. }) => {
  123. const artifactObject = _artifact.Artifact.from(artifact);
  124. this._forceVideo()._artifactReady(artifactObject);
  125. });
  126. this._channel.on('webSocket', ({
  127. webSocket
  128. }) => this.emit(_events.Events.Page.WebSocket, _network2.WebSocket.from(webSocket)));
  129. this._channel.on('worker', ({
  130. worker
  131. }) => this._onWorker(_worker.Worker.from(worker)));
  132. this.coverage = new _coverage.Coverage(this._channel);
  133. this.once(_events.Events.Page.Close, () => this._closedOrCrashedScope.close(this._closeErrorWithReason()));
  134. this.once(_events.Events.Page.Crash, () => this._closedOrCrashedScope.close(new _errors.TargetClosedError()));
  135. this._setEventToSubscriptionMapping(new Map([[_events.Events.Page.Console, 'console'], [_events.Events.Page.Dialog, 'dialog'], [_events.Events.Page.Request, 'request'], [_events.Events.Page.Response, 'response'], [_events.Events.Page.RequestFinished, 'requestFinished'], [_events.Events.Page.RequestFailed, 'requestFailed'], [_events.Events.Page.FileChooser, 'fileChooser']]));
  136. }
  137. _onFrameAttached(frame) {
  138. frame._page = this;
  139. this._frames.add(frame);
  140. if (frame._parentFrame) frame._parentFrame._childFrames.add(frame);
  141. this.emit(_events.Events.Page.FrameAttached, frame);
  142. }
  143. _onFrameDetached(frame) {
  144. this._frames.delete(frame);
  145. frame._detached = true;
  146. if (frame._parentFrame) frame._parentFrame._childFrames.delete(frame);
  147. this.emit(_events.Events.Page.FrameDetached, frame);
  148. }
  149. async _onRoute(route) {
  150. route._context = this.context();
  151. const routeHandlers = this._routes.slice();
  152. for (const routeHandler of routeHandlers) {
  153. // If the page was closed we stall all requests right away.
  154. if (this._closeWasCalled || this._browserContext._closeWasCalled) return;
  155. if (!routeHandler.matches(route.request().url())) continue;
  156. const index = this._routes.indexOf(routeHandler);
  157. if (index === -1) continue;
  158. if (routeHandler.willExpire()) this._routes.splice(index, 1);
  159. const handled = await routeHandler.handle(route);
  160. if (!this._routes.length) this._wrapApiCall(() => this._updateInterceptionPatterns(), true).catch(() => {});
  161. if (handled) return;
  162. }
  163. await this._browserContext._onRoute(route);
  164. }
  165. async _onBinding(bindingCall) {
  166. const func = this._bindings.get(bindingCall._initializer.name);
  167. if (func) {
  168. await bindingCall.call(func);
  169. return;
  170. }
  171. await this._browserContext._onBinding(bindingCall);
  172. }
  173. _onWorker(worker) {
  174. this._workers.add(worker);
  175. worker._page = this;
  176. this.emit(_events.Events.Page.Worker, worker);
  177. }
  178. _onClose() {
  179. this._closed = true;
  180. this._browserContext._pages.delete(this);
  181. this._browserContext._backgroundPages.delete(this);
  182. this._disposeHarRouters();
  183. this.emit(_events.Events.Page.Close, this);
  184. }
  185. _onCrash() {
  186. this.emit(_events.Events.Page.Crash, this);
  187. }
  188. context() {
  189. return this._browserContext;
  190. }
  191. async opener() {
  192. if (!this._opener || this._opener.isClosed()) return null;
  193. return this._opener;
  194. }
  195. mainFrame() {
  196. return this._mainFrame;
  197. }
  198. frame(frameSelector) {
  199. const name = (0, _utils.isString)(frameSelector) ? frameSelector : frameSelector.name;
  200. const url = (0, _utils.isObject)(frameSelector) ? frameSelector.url : undefined;
  201. (0, _utils.assert)(name || url, 'Either name or url matcher should be specified');
  202. return this.frames().find(f => {
  203. if (name) return f.name() === name;
  204. return (0, _network.urlMatches)(this._browserContext._options.baseURL, f.url(), url);
  205. }) || null;
  206. }
  207. frames() {
  208. return [...this._frames];
  209. }
  210. setDefaultNavigationTimeout(timeout) {
  211. this._timeoutSettings.setDefaultNavigationTimeout(timeout);
  212. this._wrapApiCall(async () => {
  213. this._channel.setDefaultNavigationTimeoutNoReply({
  214. timeout
  215. }).catch(() => {});
  216. }, true);
  217. }
  218. setDefaultTimeout(timeout) {
  219. this._timeoutSettings.setDefaultTimeout(timeout);
  220. this._wrapApiCall(async () => {
  221. this._channel.setDefaultTimeoutNoReply({
  222. timeout
  223. }).catch(() => {});
  224. }, true);
  225. }
  226. _forceVideo() {
  227. if (!this._video) this._video = new _video.Video(this, this._connection);
  228. return this._video;
  229. }
  230. video() {
  231. // Note: we are creating Video object lazily, because we do not know
  232. // BrowserContextOptions when constructing the page - it is assigned
  233. // too late during launchPersistentContext.
  234. if (!this._browserContext._options.recordVideo) return null;
  235. return this._forceVideo();
  236. }
  237. async $(selector, options) {
  238. return await this._mainFrame.$(selector, options);
  239. }
  240. async waitForSelector(selector, options) {
  241. return await this._mainFrame.waitForSelector(selector, options);
  242. }
  243. async dispatchEvent(selector, type, eventInit, options) {
  244. return await this._mainFrame.dispatchEvent(selector, type, eventInit, options);
  245. }
  246. async evaluateHandle(pageFunction, arg) {
  247. (0, _jsHandle.assertMaxArguments)(arguments.length, 2);
  248. return await this._mainFrame.evaluateHandle(pageFunction, arg);
  249. }
  250. async $eval(selector, pageFunction, arg) {
  251. (0, _jsHandle.assertMaxArguments)(arguments.length, 3);
  252. return await this._mainFrame.$eval(selector, pageFunction, arg);
  253. }
  254. async $$eval(selector, pageFunction, arg) {
  255. (0, _jsHandle.assertMaxArguments)(arguments.length, 3);
  256. return await this._mainFrame.$$eval(selector, pageFunction, arg);
  257. }
  258. async $$(selector) {
  259. return await this._mainFrame.$$(selector);
  260. }
  261. async addScriptTag(options = {}) {
  262. return await this._mainFrame.addScriptTag(options);
  263. }
  264. async addStyleTag(options = {}) {
  265. return await this._mainFrame.addStyleTag(options);
  266. }
  267. async exposeFunction(name, callback) {
  268. await this._channel.exposeBinding({
  269. name
  270. });
  271. const binding = (source, ...args) => callback(...args);
  272. this._bindings.set(name, binding);
  273. }
  274. async exposeBinding(name, callback, options = {}) {
  275. await this._channel.exposeBinding({
  276. name,
  277. needsHandle: options.handle
  278. });
  279. this._bindings.set(name, callback);
  280. }
  281. async setExtraHTTPHeaders(headers) {
  282. (0, _network2.validateHeaders)(headers);
  283. await this._channel.setExtraHTTPHeaders({
  284. headers: (0, _utils.headersObjectToArray)(headers)
  285. });
  286. }
  287. url() {
  288. return this._mainFrame.url();
  289. }
  290. async content() {
  291. return await this._mainFrame.content();
  292. }
  293. async setContent(html, options) {
  294. return await this._mainFrame.setContent(html, options);
  295. }
  296. async goto(url, options) {
  297. return await this._mainFrame.goto(url, options);
  298. }
  299. async reload(options = {}) {
  300. const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
  301. return _network2.Response.fromNullable((await this._channel.reload({
  302. ...options,
  303. waitUntil
  304. })).response);
  305. }
  306. async waitForLoadState(state, options) {
  307. return await this._mainFrame.waitForLoadState(state, options);
  308. }
  309. async waitForNavigation(options) {
  310. return await this._mainFrame.waitForNavigation(options);
  311. }
  312. async waitForURL(url, options) {
  313. return await this._mainFrame.waitForURL(url, options);
  314. }
  315. async waitForRequest(urlOrPredicate, options = {}) {
  316. const predicate = async request => {
  317. if ((0, _utils.isString)(urlOrPredicate) || (0, _utils.isRegExp)(urlOrPredicate)) return (0, _network.urlMatches)(this._browserContext._options.baseURL, request.url(), urlOrPredicate);
  318. return await urlOrPredicate(request);
  319. };
  320. const trimmedUrl = trimUrl(urlOrPredicate);
  321. const logLine = trimmedUrl ? `waiting for request ${trimmedUrl}` : undefined;
  322. return await this._waitForEvent(_events.Events.Page.Request, {
  323. predicate,
  324. timeout: options.timeout
  325. }, logLine);
  326. }
  327. async waitForResponse(urlOrPredicate, options = {}) {
  328. const predicate = async response => {
  329. if ((0, _utils.isString)(urlOrPredicate) || (0, _utils.isRegExp)(urlOrPredicate)) return (0, _network.urlMatches)(this._browserContext._options.baseURL, response.url(), urlOrPredicate);
  330. return await urlOrPredicate(response);
  331. };
  332. const trimmedUrl = trimUrl(urlOrPredicate);
  333. const logLine = trimmedUrl ? `waiting for response ${trimmedUrl}` : undefined;
  334. return await this._waitForEvent(_events.Events.Page.Response, {
  335. predicate,
  336. timeout: options.timeout
  337. }, logLine);
  338. }
  339. async waitForEvent(event, optionsOrPredicate = {}) {
  340. return await this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`);
  341. }
  342. _closeErrorWithReason() {
  343. return new _errors.TargetClosedError(this._closeReason || this._browserContext._effectiveCloseReason());
  344. }
  345. async _waitForEvent(event, optionsOrPredicate, logLine) {
  346. return await this._wrapApiCall(async () => {
  347. const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);
  348. const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;
  349. const waiter = _waiter.Waiter.createForEvent(this, event);
  350. if (logLine) waiter.log(logLine);
  351. waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
  352. if (event !== _events.Events.Page.Crash) waiter.rejectOnEvent(this, _events.Events.Page.Crash, new Error('Page crashed'));
  353. if (event !== _events.Events.Page.Close) waiter.rejectOnEvent(this, _events.Events.Page.Close, () => this._closeErrorWithReason());
  354. const result = await waiter.waitForEvent(this, event, predicate);
  355. waiter.dispose();
  356. return result;
  357. });
  358. }
  359. async goBack(options = {}) {
  360. const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
  361. return _network2.Response.fromNullable((await this._channel.goBack({
  362. ...options,
  363. waitUntil
  364. })).response);
  365. }
  366. async goForward(options = {}) {
  367. const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
  368. return _network2.Response.fromNullable((await this._channel.goForward({
  369. ...options,
  370. waitUntil
  371. })).response);
  372. }
  373. async emulateMedia(options = {}) {
  374. await this._channel.emulateMedia({
  375. media: options.media === null ? 'no-override' : options.media,
  376. colorScheme: options.colorScheme === null ? 'no-override' : options.colorScheme,
  377. reducedMotion: options.reducedMotion === null ? 'no-override' : options.reducedMotion,
  378. forcedColors: options.forcedColors === null ? 'no-override' : options.forcedColors
  379. });
  380. }
  381. async setViewportSize(viewportSize) {
  382. this._viewportSize = viewportSize;
  383. await this._channel.setViewportSize({
  384. viewportSize
  385. });
  386. }
  387. viewportSize() {
  388. return this._viewportSize;
  389. }
  390. async evaluate(pageFunction, arg) {
  391. (0, _jsHandle.assertMaxArguments)(arguments.length, 2);
  392. return await this._mainFrame.evaluate(pageFunction, arg);
  393. }
  394. async addInitScript(script, arg) {
  395. const source = await (0, _clientHelper.evaluationScript)(script, arg);
  396. await this._channel.addInitScript({
  397. source
  398. });
  399. }
  400. async route(url, handler, options = {}) {
  401. this._routes.unshift(new _network2.RouteHandler(this._browserContext._options.baseURL, url, handler, options.times));
  402. await this._updateInterceptionPatterns();
  403. }
  404. async routeFromHAR(har, options = {}) {
  405. if (options.update) {
  406. await this._browserContext._recordIntoHAR(har, this, options);
  407. return;
  408. }
  409. const harRouter = await _harRouter.HarRouter.create(this._connection.localUtils(), har, options.notFound || 'abort', {
  410. urlMatch: options.url
  411. });
  412. this._harRouters.push(harRouter);
  413. await harRouter.addPageRoute(this);
  414. }
  415. _disposeHarRouters() {
  416. this._harRouters.forEach(router => router.dispose());
  417. this._harRouters = [];
  418. }
  419. async unrouteAll(options) {
  420. await this._unrouteInternal(this._routes, [], options === null || options === void 0 ? void 0 : options.behavior);
  421. this._disposeHarRouters();
  422. }
  423. async unroute(url, handler) {
  424. const removed = [];
  425. const remaining = [];
  426. for (const route of this._routes) {
  427. if ((0, _utils.urlMatchesEqual)(route.url, url) && (!handler || route.handler === handler)) removed.push(route);else remaining.push(route);
  428. }
  429. await this._unrouteInternal(removed, remaining, 'default');
  430. }
  431. async _unrouteInternal(removed, remaining, behavior) {
  432. this._routes = remaining;
  433. await this._updateInterceptionPatterns();
  434. if (!behavior || behavior === 'default') return;
  435. const promises = removed.map(routeHandler => routeHandler.stop(behavior));
  436. await Promise.all(promises);
  437. }
  438. async _updateInterceptionPatterns() {
  439. const patterns = _network2.RouteHandler.prepareInterceptionPatterns(this._routes);
  440. await this._channel.setNetworkInterceptionPatterns({
  441. patterns
  442. });
  443. }
  444. async screenshot(options = {}) {
  445. const copy = {
  446. ...options,
  447. mask: undefined
  448. };
  449. if (!copy.type) copy.type = (0, _elementHandle.determineScreenshotType)(options);
  450. if (options.mask) {
  451. copy.mask = options.mask.map(locator => ({
  452. frame: locator._frame._channel,
  453. selector: locator._selector
  454. }));
  455. }
  456. const result = await this._channel.screenshot(copy);
  457. if (options.path) {
  458. await (0, _fileUtils.mkdirIfNeeded)(options.path);
  459. await _fs.default.promises.writeFile(options.path, result.binary);
  460. }
  461. return result.binary;
  462. }
  463. async _expectScreenshot(options) {
  464. var _options$screenshotOp, _options$screenshotOp2;
  465. const mask = (_options$screenshotOp = options.screenshotOptions) !== null && _options$screenshotOp !== void 0 && _options$screenshotOp.mask ? (_options$screenshotOp2 = options.screenshotOptions) === null || _options$screenshotOp2 === void 0 ? void 0 : _options$screenshotOp2.mask.map(locator => ({
  466. frame: locator._frame._channel,
  467. selector: locator._selector
  468. })) : undefined;
  469. const locator = options.locator ? {
  470. frame: options.locator._frame._channel,
  471. selector: options.locator._selector
  472. } : undefined;
  473. return await this._channel.expectScreenshot({
  474. ...options,
  475. isNot: !!options.isNot,
  476. locator,
  477. screenshotOptions: {
  478. ...options.screenshotOptions,
  479. mask
  480. }
  481. });
  482. }
  483. async title() {
  484. return await this._mainFrame.title();
  485. }
  486. async bringToFront() {
  487. await this._channel.bringToFront();
  488. }
  489. async [_Symbol$asyncDispose]() {
  490. await this.close();
  491. }
  492. async close(options = {}) {
  493. this._closeReason = options.reason;
  494. this._closeWasCalled = true;
  495. try {
  496. if (this._ownedContext) await this._ownedContext.close();else await this._channel.close(options);
  497. } catch (e) {
  498. if ((0, _errors.isTargetClosedError)(e) && !options.runBeforeUnload) return;
  499. throw e;
  500. }
  501. }
  502. isClosed() {
  503. return this._closed;
  504. }
  505. async click(selector, options) {
  506. return await this._mainFrame.click(selector, options);
  507. }
  508. async dragAndDrop(source, target, options) {
  509. return await this._mainFrame.dragAndDrop(source, target, options);
  510. }
  511. async dblclick(selector, options) {
  512. return await this._mainFrame.dblclick(selector, options);
  513. }
  514. async tap(selector, options) {
  515. return await this._mainFrame.tap(selector, options);
  516. }
  517. async fill(selector, value, options) {
  518. return await this._mainFrame.fill(selector, value, options);
  519. }
  520. locator(selector, options) {
  521. return this.mainFrame().locator(selector, options);
  522. }
  523. getByTestId(testId) {
  524. return this.mainFrame().getByTestId(testId);
  525. }
  526. getByAltText(text, options) {
  527. return this.mainFrame().getByAltText(text, options);
  528. }
  529. getByLabel(text, options) {
  530. return this.mainFrame().getByLabel(text, options);
  531. }
  532. getByPlaceholder(text, options) {
  533. return this.mainFrame().getByPlaceholder(text, options);
  534. }
  535. getByText(text, options) {
  536. return this.mainFrame().getByText(text, options);
  537. }
  538. getByTitle(text, options) {
  539. return this.mainFrame().getByTitle(text, options);
  540. }
  541. getByRole(role, options = {}) {
  542. return this.mainFrame().getByRole(role, options);
  543. }
  544. frameLocator(selector) {
  545. return this.mainFrame().frameLocator(selector);
  546. }
  547. async focus(selector, options) {
  548. return await this._mainFrame.focus(selector, options);
  549. }
  550. async textContent(selector, options) {
  551. return await this._mainFrame.textContent(selector, options);
  552. }
  553. async innerText(selector, options) {
  554. return await this._mainFrame.innerText(selector, options);
  555. }
  556. async innerHTML(selector, options) {
  557. return await this._mainFrame.innerHTML(selector, options);
  558. }
  559. async getAttribute(selector, name, options) {
  560. return await this._mainFrame.getAttribute(selector, name, options);
  561. }
  562. async inputValue(selector, options) {
  563. return await this._mainFrame.inputValue(selector, options);
  564. }
  565. async isChecked(selector, options) {
  566. return await this._mainFrame.isChecked(selector, options);
  567. }
  568. async isDisabled(selector, options) {
  569. return await this._mainFrame.isDisabled(selector, options);
  570. }
  571. async isEditable(selector, options) {
  572. return await this._mainFrame.isEditable(selector, options);
  573. }
  574. async isEnabled(selector, options) {
  575. return await this._mainFrame.isEnabled(selector, options);
  576. }
  577. async isHidden(selector, options) {
  578. return await this._mainFrame.isHidden(selector, options);
  579. }
  580. async isVisible(selector, options) {
  581. return await this._mainFrame.isVisible(selector, options);
  582. }
  583. async hover(selector, options) {
  584. return await this._mainFrame.hover(selector, options);
  585. }
  586. async selectOption(selector, values, options) {
  587. return await this._mainFrame.selectOption(selector, values, options);
  588. }
  589. async setInputFiles(selector, files, options) {
  590. return await this._mainFrame.setInputFiles(selector, files, options);
  591. }
  592. async type(selector, text, options) {
  593. return await this._mainFrame.type(selector, text, options);
  594. }
  595. async press(selector, key, options) {
  596. return await this._mainFrame.press(selector, key, options);
  597. }
  598. async check(selector, options) {
  599. return await this._mainFrame.check(selector, options);
  600. }
  601. async uncheck(selector, options) {
  602. return await this._mainFrame.uncheck(selector, options);
  603. }
  604. async setChecked(selector, checked, options) {
  605. return await this._mainFrame.setChecked(selector, checked, options);
  606. }
  607. async waitForTimeout(timeout) {
  608. return await this._mainFrame.waitForTimeout(timeout);
  609. }
  610. async waitForFunction(pageFunction, arg, options) {
  611. return await this._mainFrame.waitForFunction(pageFunction, arg, options);
  612. }
  613. workers() {
  614. return [...this._workers];
  615. }
  616. async pause() {
  617. var _this$_instrumentatio;
  618. if (require('inspector').url()) return;
  619. const defaultNavigationTimeout = this._browserContext._timeoutSettings.defaultNavigationTimeout();
  620. const defaultTimeout = this._browserContext._timeoutSettings.defaultTimeout();
  621. this._browserContext.setDefaultNavigationTimeout(0);
  622. this._browserContext.setDefaultTimeout(0);
  623. (_this$_instrumentatio = this._instrumentation) === null || _this$_instrumentatio === void 0 ? void 0 : _this$_instrumentatio.onWillPause();
  624. await this._closedOrCrashedScope.safeRace(this.context()._channel.pause());
  625. this._browserContext.setDefaultNavigationTimeout(defaultNavigationTimeout);
  626. this._browserContext.setDefaultTimeout(defaultTimeout);
  627. }
  628. async pdf(options = {}) {
  629. const transportOptions = {
  630. ...options
  631. };
  632. if (transportOptions.margin) transportOptions.margin = {
  633. ...transportOptions.margin
  634. };
  635. if (typeof options.width === 'number') transportOptions.width = options.width + 'px';
  636. if (typeof options.height === 'number') transportOptions.height = options.height + 'px';
  637. for (const margin of ['top', 'right', 'bottom', 'left']) {
  638. const index = margin;
  639. if (options.margin && typeof options.margin[index] === 'number') transportOptions.margin[index] = transportOptions.margin[index] + 'px';
  640. }
  641. const result = await this._channel.pdf(transportOptions);
  642. if (options.path) {
  643. await _fs.default.promises.mkdir(_path.default.dirname(options.path), {
  644. recursive: true
  645. });
  646. await _fs.default.promises.writeFile(options.path, result.pdf);
  647. }
  648. return result.pdf;
  649. }
  650. }
  651. exports.Page = Page;
  652. class BindingCall extends _channelOwner.ChannelOwner {
  653. static from(channel) {
  654. return channel._object;
  655. }
  656. constructor(parent, type, guid, initializer) {
  657. super(parent, type, guid, initializer);
  658. }
  659. async call(func) {
  660. try {
  661. const frame = _frame.Frame.from(this._initializer.frame);
  662. const source = {
  663. context: frame._page.context(),
  664. page: frame._page,
  665. frame
  666. };
  667. let result;
  668. if (this._initializer.handle) result = await func(source, _jsHandle.JSHandle.from(this._initializer.handle));else result = await func(source, ...this._initializer.args.map(_jsHandle.parseResult));
  669. this._channel.resolve({
  670. result: (0, _jsHandle.serializeArgument)(result)
  671. }).catch(() => {});
  672. } catch (e) {
  673. this._channel.reject({
  674. error: (0, _errors.serializeError)(e)
  675. }).catch(() => {});
  676. }
  677. }
  678. }
  679. exports.BindingCall = BindingCall;
  680. function trimUrl(param) {
  681. if ((0, _utils.isRegExp)(param)) return `/${(0, _stringUtils.trimStringWithEllipsis)(param.source, 50)}/${param.flags}`;
  682. if ((0, _utils.isString)(param)) return `"${(0, _stringUtils.trimStringWithEllipsis)(param, 50)}"`;
  683. }