dom.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.NonRecoverableDOMError = exports.InjectedScriptPollHandler = exports.FrameExecutionContext = exports.ElementHandle = void 0;
  6. exports.assertDone = assertDone;
  7. exports.isNonRecoverableDOMError = isNonRecoverableDOMError;
  8. exports.kUnableToAdoptErrorMessage = void 0;
  9. exports.throwRetargetableDOMError = throwRetargetableDOMError;
  10. var injectedScriptSource = _interopRequireWildcard(require("../generated/injectedScriptSource"));
  11. var _protocolError = require("./protocolError");
  12. var js = _interopRequireWildcard(require("./javascript"));
  13. var _progress = require("./progress");
  14. var _utils = require("../utils");
  15. var _fileUploadUtils = require("./fileUploadUtils");
  16. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  17. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  18. /**
  19. * Copyright (c) Microsoft Corporation.
  20. *
  21. * Licensed under the Apache License, Version 2.0 (the "License");
  22. * you may not use this file except in compliance with the License.
  23. * You may obtain a copy of the License at
  24. *
  25. * http://www.apache.org/licenses/LICENSE-2.0
  26. *
  27. * Unless required by applicable law or agreed to in writing, software
  28. * distributed under the License is distributed on an "AS IS" BASIS,
  29. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  30. * See the License for the specific language governing permissions and
  31. * limitations under the License.
  32. */
  33. class NonRecoverableDOMError extends Error {}
  34. exports.NonRecoverableDOMError = NonRecoverableDOMError;
  35. function isNonRecoverableDOMError(error) {
  36. return error instanceof NonRecoverableDOMError;
  37. }
  38. class FrameExecutionContext extends js.ExecutionContext {
  39. constructor(delegate, frame, world) {
  40. super(frame, delegate, world || 'content-script');
  41. this.frame = void 0;
  42. this._injectedScriptPromise = void 0;
  43. this.world = void 0;
  44. this.frame = frame;
  45. this.world = world;
  46. }
  47. adoptIfNeeded(handle) {
  48. if (handle instanceof ElementHandle && handle._context !== this) return this.frame._page._delegate.adoptElementHandle(handle, this);
  49. return null;
  50. }
  51. async evaluate(pageFunction, arg) {
  52. return js.evaluate(this, true /* returnByValue */, pageFunction, arg);
  53. }
  54. async evaluateHandle(pageFunction, arg) {
  55. return js.evaluate(this, false /* returnByValue */, pageFunction, arg);
  56. }
  57. async evaluateExpression(expression, options, arg) {
  58. return js.evaluateExpression(this, expression, {
  59. ...options,
  60. returnByValue: true
  61. }, arg);
  62. }
  63. async evaluateExpressionHandle(expression, options, arg) {
  64. return js.evaluateExpression(this, expression, {
  65. ...options,
  66. returnByValue: false
  67. }, arg);
  68. }
  69. createHandle(remoteObject) {
  70. if (this.frame._page._delegate.isElementHandle(remoteObject)) return new ElementHandle(this, remoteObject.objectId);
  71. return super.createHandle(remoteObject);
  72. }
  73. injectedScript() {
  74. if (!this._injectedScriptPromise) {
  75. const custom = [];
  76. const selectorsRegistry = this.frame._page.context().selectors();
  77. for (const [name, {
  78. source
  79. }] of selectorsRegistry._engines) custom.push(`{ name: '${name}', engine: (${source}) }`);
  80. const sdkLanguage = this.frame.attribution.playwright.options.sdkLanguage;
  81. const source = `
  82. (() => {
  83. const module = {};
  84. ${injectedScriptSource.source}
  85. return new (module.exports.InjectedScript())(
  86. globalThis,
  87. ${(0, _utils.isUnderTest)()},
  88. "${sdkLanguage}",
  89. ${JSON.stringify(selectorsRegistry.testIdAttributeName())},
  90. ${this.frame._page._delegate.rafCountForStablePosition()},
  91. "${this.frame._page._browserContext._browser.options.name}",
  92. [${custom.join(',\n')}]
  93. );
  94. })();
  95. `;
  96. this._injectedScriptPromise = this.rawEvaluateHandle(source).then(objectId => new js.JSHandle(this, 'object', 'InjectedScript', objectId));
  97. }
  98. return this._injectedScriptPromise;
  99. }
  100. }
  101. exports.FrameExecutionContext = FrameExecutionContext;
  102. class ElementHandle extends js.JSHandle {
  103. constructor(context, objectId) {
  104. super(context, 'node', undefined, objectId);
  105. this.__elementhandle = true;
  106. this._page = void 0;
  107. this._frame = void 0;
  108. this._page = context.frame._page;
  109. this._frame = context.frame;
  110. this._initializePreview().catch(e => {});
  111. }
  112. async _initializePreview() {
  113. const utility = await this._context.injectedScript();
  114. this._setPreview(await utility.evaluate((injected, e) => 'JSHandle@' + injected.previewNode(e), this));
  115. }
  116. asElement() {
  117. return this;
  118. }
  119. async evaluateInUtility(pageFunction, arg) {
  120. try {
  121. const utility = await this._frame._utilityContext();
  122. return await utility.evaluate(pageFunction, [await utility.injectedScript(), this, arg]);
  123. } catch (e) {
  124. if (js.isJavaScriptErrorInEvaluate(e) || (0, _protocolError.isSessionClosedError)(e)) throw e;
  125. return 'error:notconnected';
  126. }
  127. }
  128. async evaluateHandleInUtility(pageFunction, arg) {
  129. try {
  130. const utility = await this._frame._utilityContext();
  131. return await utility.evaluateHandle(pageFunction, [await utility.injectedScript(), this, arg]);
  132. } catch (e) {
  133. if (js.isJavaScriptErrorInEvaluate(e) || (0, _protocolError.isSessionClosedError)(e)) throw e;
  134. return 'error:notconnected';
  135. }
  136. }
  137. async evaluatePoll(progress, pageFunction, arg) {
  138. try {
  139. const utility = await this._frame._utilityContext();
  140. const poll = await utility.evaluateHandle(pageFunction, [await utility.injectedScript(), this, arg]);
  141. const pollHandler = new InjectedScriptPollHandler(progress, poll);
  142. return await pollHandler.finish();
  143. } catch (e) {
  144. if (js.isJavaScriptErrorInEvaluate(e) || (0, _protocolError.isSessionClosedError)(e)) throw e;
  145. return 'error:notconnected';
  146. }
  147. }
  148. async ownerFrame() {
  149. const frameId = await this._page._delegate.getOwnerFrame(this);
  150. if (!frameId) return null;
  151. const frame = this._page._frameManager.frame(frameId);
  152. if (frame) return frame;
  153. for (const page of this._page._browserContext.pages()) {
  154. const frame = page._frameManager.frame(frameId);
  155. if (frame) return frame;
  156. }
  157. return null;
  158. }
  159. async isIframeElement() {
  160. return this.evaluateInUtility(([injected, node]) => node && (node.nodeName === 'IFRAME' || node.nodeName === 'FRAME'), {});
  161. }
  162. async contentFrame() {
  163. const isFrameElement = throwRetargetableDOMError(await this.isIframeElement());
  164. if (!isFrameElement) return null;
  165. return this._page._delegate.getContentFrame(this);
  166. }
  167. async getAttribute(metadata, name) {
  168. return this._frame.getAttribute(metadata, ':scope', name, {}, this);
  169. }
  170. async inputValue(metadata) {
  171. return this._frame.inputValue(metadata, ':scope', {}, this);
  172. }
  173. async textContent(metadata) {
  174. return this._frame.textContent(metadata, ':scope', {}, this);
  175. }
  176. async innerText(metadata) {
  177. return this._frame.innerText(metadata, ':scope', {}, this);
  178. }
  179. async innerHTML(metadata) {
  180. return this._frame.innerHTML(metadata, ':scope', {}, this);
  181. }
  182. async dispatchEvent(metadata, type, eventInit = {}) {
  183. return this._frame.dispatchEvent(metadata, ':scope', type, eventInit, {}, this);
  184. }
  185. async _scrollRectIntoViewIfNeeded(rect) {
  186. return await this._page._delegate.scrollRectIntoViewIfNeeded(this, rect);
  187. }
  188. async _waitAndScrollIntoViewIfNeeded(progress, waitForVisible) {
  189. const timeouts = [0, 50, 100, 250];
  190. while (progress.isRunning()) {
  191. assertDone(throwRetargetableDOMError(await this._waitForElementStates(progress, waitForVisible ? ['visible', 'stable'] : ['stable'], false /* force */)));
  192. progress.throwIfAborted(); // Avoid action that has side-effects.
  193. const result = throwRetargetableDOMError(await this._scrollRectIntoViewIfNeeded());
  194. if (result === 'error:notvisible') {
  195. if (!waitForVisible) {
  196. var _timeouts$shift;
  197. // Wait for a timeout to avoid retrying too often when not waiting for visible.
  198. // If we wait for visible, this should be covered by _waitForElementStates instead.
  199. const timeout = (_timeouts$shift = timeouts.shift()) !== null && _timeouts$shift !== void 0 ? _timeouts$shift : 500;
  200. progress.log(` element is not displayed, retrying in ${timeout}ms`);
  201. await new Promise(f => setTimeout(f, timeout));
  202. }
  203. continue;
  204. }
  205. assertDone(result);
  206. return;
  207. }
  208. }
  209. async scrollIntoViewIfNeeded(metadata, options = {}) {
  210. const controller = new _progress.ProgressController(metadata, this);
  211. return controller.run(progress => this._waitAndScrollIntoViewIfNeeded(progress, false /* waitForVisible */), this._page._timeoutSettings.timeout(options));
  212. }
  213. async _clickablePoint() {
  214. const intersectQuadWithViewport = quad => {
  215. return quad.map(point => ({
  216. x: Math.min(Math.max(point.x, 0), metrics.width),
  217. y: Math.min(Math.max(point.y, 0), metrics.height)
  218. }));
  219. };
  220. const computeQuadArea = quad => {
  221. // Compute sum of all directed areas of adjacent triangles
  222. // https://en.wikipedia.org/wiki/Polygon#Simple_polygons
  223. let area = 0;
  224. for (let i = 0; i < quad.length; ++i) {
  225. const p1 = quad[i];
  226. const p2 = quad[(i + 1) % quad.length];
  227. area += (p1.x * p2.y - p2.x * p1.y) / 2;
  228. }
  229. return Math.abs(area);
  230. };
  231. const [quads, metrics] = await Promise.all([this._page._delegate.getContentQuads(this), this._page.mainFrame()._utilityContext().then(utility => utility.evaluate(() => ({
  232. width: innerWidth,
  233. height: innerHeight
  234. })))]);
  235. if (!quads || !quads.length) return 'error:notvisible';
  236. // Allow 1x1 elements. Compensate for rounding errors by comparing with 0.99 instead.
  237. const filtered = quads.map(quad => intersectQuadWithViewport(quad)).filter(quad => computeQuadArea(quad) > 0.99);
  238. if (!filtered.length) return 'error:notinviewport';
  239. // Return the middle point of the first quad.
  240. const result = {
  241. x: 0,
  242. y: 0
  243. };
  244. for (const point of filtered[0]) {
  245. result.x += point.x / 4;
  246. result.y += point.y / 4;
  247. }
  248. compensateHalfIntegerRoundingError(result);
  249. return result;
  250. }
  251. async _offsetPoint(offset) {
  252. const [box, border] = await Promise.all([this.boundingBox(), this.evaluateInUtility(([injected, node]) => injected.getElementBorderWidth(node), {}).catch(e => {})]);
  253. if (!box || !border) return 'error:notvisible';
  254. if (border === 'error:notconnected') return border;
  255. // Make point relative to the padding box to align with offsetX/offsetY.
  256. return {
  257. x: box.x + border.left + offset.x,
  258. y: box.y + border.top + offset.y
  259. };
  260. }
  261. async _retryPointerAction(progress, actionName, waitForEnabled, action, options) {
  262. let retry = 0;
  263. // We progressively wait longer between retries, up to 500ms.
  264. const waitTime = [0, 20, 100, 100, 500];
  265. // By default, we scroll with protocol method to reveal the action point.
  266. // However, that might not work to scroll from under position:sticky elements
  267. // that overlay the target element. To fight this, we cycle through different
  268. // scroll alignments. This works in most scenarios.
  269. const scrollOptions = [undefined, {
  270. block: 'end',
  271. inline: 'end'
  272. }, {
  273. block: 'center',
  274. inline: 'center'
  275. }, {
  276. block: 'start',
  277. inline: 'start'
  278. }];
  279. while (progress.isRunning()) {
  280. if (retry) {
  281. progress.log(`retrying ${actionName} action${options.trial ? ' (trial run)' : ''}, attempt #${retry}`);
  282. const timeout = waitTime[Math.min(retry - 1, waitTime.length - 1)];
  283. if (timeout) {
  284. progress.log(` waiting ${timeout}ms`);
  285. const result = await this.evaluateInUtility(([injected, node, timeout]) => new Promise(f => setTimeout(f, timeout)), timeout);
  286. if (result === 'error:notconnected') return result;
  287. }
  288. } else {
  289. progress.log(`attempting ${actionName} action${options.trial ? ' (trial run)' : ''}`);
  290. }
  291. const forceScrollOptions = scrollOptions[retry % scrollOptions.length];
  292. const result = await this._performPointerAction(progress, actionName, waitForEnabled, action, forceScrollOptions, options);
  293. ++retry;
  294. if (result === 'error:notvisible') {
  295. if (options.force) throw new NonRecoverableDOMError('Element is not visible');
  296. progress.log(' element is not visible');
  297. continue;
  298. }
  299. if (result === 'error:notinviewport') {
  300. if (options.force) throw new NonRecoverableDOMError('Element is outside of the viewport');
  301. progress.log(' element is outside of the viewport');
  302. continue;
  303. }
  304. if (typeof result === 'object' && 'hitTargetDescription' in result) {
  305. progress.log(` ${result.hitTargetDescription} intercepts pointer events`);
  306. continue;
  307. }
  308. return result;
  309. }
  310. return 'done';
  311. }
  312. async _performPointerAction(progress, actionName, waitForEnabled, action, forceScrollOptions, options) {
  313. const {
  314. force = false,
  315. position
  316. } = options;
  317. const doScrollIntoView = async () => {
  318. if (forceScrollOptions) {
  319. return await this.evaluateInUtility(([injected, node, options]) => {
  320. if (node.nodeType === 1 /* Node.ELEMENT_NODE */) node.scrollIntoView(options);
  321. return 'done';
  322. }, forceScrollOptions);
  323. }
  324. return await this._scrollRectIntoViewIfNeeded(position ? {
  325. x: position.x,
  326. y: position.y,
  327. width: 0,
  328. height: 0
  329. } : undefined);
  330. };
  331. if (this._frame.parentFrame()) {
  332. // Best-effort scroll to make sure any iframes containing this element are scrolled
  333. // into view and visible, so they are not throttled.
  334. // See https://github.com/microsoft/playwright/issues/27196 for an example.
  335. progress.throwIfAborted(); // Avoid action that has side-effects.
  336. await doScrollIntoView().catch(() => {});
  337. }
  338. if (options.__testHookBeforeStable) await options.__testHookBeforeStable();
  339. const result = await this._waitForElementStates(progress, waitForEnabled ? ['visible', 'enabled', 'stable'] : ['visible', 'stable'], force);
  340. if (result !== 'done') return result;
  341. if (options.__testHookAfterStable) await options.__testHookAfterStable();
  342. progress.log(' scrolling into view if needed');
  343. progress.throwIfAborted(); // Avoid action that has side-effects.
  344. const scrolled = await doScrollIntoView();
  345. if (scrolled !== 'done') return scrolled;
  346. progress.log(' done scrolling');
  347. const maybePoint = position ? await this._offsetPoint(position) : await this._clickablePoint();
  348. if (typeof maybePoint === 'string') return maybePoint;
  349. const point = roundPoint(maybePoint);
  350. progress.metadata.point = point;
  351. await progress.beforeInputAction(this);
  352. let hitTargetInterceptionHandle;
  353. if (!options.force) {
  354. if (options.__testHookBeforeHitTarget) await options.__testHookBeforeHitTarget();
  355. const frameCheckResult = await this._checkFrameIsHitTarget(point);
  356. if (frameCheckResult === 'error:notconnected' || 'hitTargetDescription' in frameCheckResult) return frameCheckResult;
  357. const hitPoint = frameCheckResult.framePoint;
  358. const actionType = actionName === 'move and up' ? 'drag' : actionName === 'hover' || actionName === 'tap' ? actionName : 'mouse';
  359. const handle = await this.evaluateHandleInUtility(([injected, node, {
  360. actionType,
  361. hitPoint,
  362. trial
  363. }]) => injected.setupHitTargetInterceptor(node, actionType, hitPoint, trial), {
  364. actionType,
  365. hitPoint,
  366. trial: !!options.trial
  367. });
  368. if (handle === 'error:notconnected') return handle;
  369. if (!handle._objectId) {
  370. const error = handle.rawValue();
  371. if (error === 'error:notconnected') return error;
  372. return {
  373. hitTargetDescription: error
  374. };
  375. }
  376. hitTargetInterceptionHandle = handle;
  377. progress.cleanupWhenAborted(() => {
  378. // Do not await here, just in case the renderer is stuck (e.g. on alert)
  379. // and we won't be able to cleanup.
  380. hitTargetInterceptionHandle.evaluate(h => h.stop()).catch(e => {});
  381. hitTargetInterceptionHandle.dispose();
  382. });
  383. }
  384. const actionResult = await this._page._frameManager.waitForSignalsCreatedBy(progress, options.noWaitAfter, async () => {
  385. if (options.__testHookBeforePointerAction) await options.__testHookBeforePointerAction();
  386. progress.throwIfAborted(); // Avoid action that has side-effects.
  387. let restoreModifiers;
  388. if (options && options.modifiers) restoreModifiers = await this._page.keyboard._ensureModifiers(options.modifiers);
  389. progress.log(` performing ${actionName} action`);
  390. await action(point);
  391. if (restoreModifiers) await this._page.keyboard._ensureModifiers(restoreModifiers);
  392. if (hitTargetInterceptionHandle) {
  393. const stopHitTargetInterception = hitTargetInterceptionHandle.evaluate(h => h.stop()).catch(e => 'done').finally(() => {
  394. var _hitTargetInterceptio;
  395. (_hitTargetInterceptio = hitTargetInterceptionHandle) === null || _hitTargetInterceptio === void 0 ? void 0 : _hitTargetInterceptio.dispose();
  396. });
  397. if (!options.noWaitAfter) {
  398. // When noWaitAfter is passed, we do not want to accidentally stall on
  399. // non-committed navigation blocking the evaluate.
  400. const hitTargetResult = await stopHitTargetInterception;
  401. if (hitTargetResult !== 'done') return hitTargetResult;
  402. }
  403. }
  404. progress.log(` ${options.trial ? 'trial ' : ''}${actionName} action done`);
  405. progress.log(' waiting for scheduled navigations to finish');
  406. if (options.__testHookAfterPointerAction) await options.__testHookAfterPointerAction();
  407. return 'done';
  408. }, 'input');
  409. if (actionResult !== 'done') return actionResult;
  410. progress.log(' navigations have finished');
  411. return 'done';
  412. }
  413. async hover(metadata, options) {
  414. const controller = new _progress.ProgressController(metadata, this);
  415. return controller.run(async progress => {
  416. const result = await this._hover(progress, options);
  417. return assertDone(throwRetargetableDOMError(result));
  418. }, this._page._timeoutSettings.timeout(options));
  419. }
  420. _hover(progress, options) {
  421. return this._retryPointerAction(progress, 'hover', false /* waitForEnabled */, point => this._page.mouse.move(point.x, point.y), options);
  422. }
  423. async click(metadata, options = {}) {
  424. const controller = new _progress.ProgressController(metadata, this);
  425. return controller.run(async progress => {
  426. const result = await this._click(progress, options);
  427. return assertDone(throwRetargetableDOMError(result));
  428. }, this._page._timeoutSettings.timeout(options));
  429. }
  430. _click(progress, options) {
  431. return this._retryPointerAction(progress, 'click', true /* waitForEnabled */, point => this._page.mouse.click(point.x, point.y, options), options);
  432. }
  433. async dblclick(metadata, options) {
  434. const controller = new _progress.ProgressController(metadata, this);
  435. return controller.run(async progress => {
  436. const result = await this._dblclick(progress, options);
  437. return assertDone(throwRetargetableDOMError(result));
  438. }, this._page._timeoutSettings.timeout(options));
  439. }
  440. _dblclick(progress, options) {
  441. return this._retryPointerAction(progress, 'dblclick', true /* waitForEnabled */, point => this._page.mouse.dblclick(point.x, point.y, options), options);
  442. }
  443. async tap(metadata, options = {}) {
  444. const controller = new _progress.ProgressController(metadata, this);
  445. return controller.run(async progress => {
  446. const result = await this._tap(progress, options);
  447. return assertDone(throwRetargetableDOMError(result));
  448. }, this._page._timeoutSettings.timeout(options));
  449. }
  450. _tap(progress, options) {
  451. return this._retryPointerAction(progress, 'tap', true /* waitForEnabled */, point => this._page.touchscreen.tap(point.x, point.y), options);
  452. }
  453. async selectOption(metadata, elements, values, options) {
  454. const controller = new _progress.ProgressController(metadata, this);
  455. return controller.run(async progress => {
  456. const result = await this._selectOption(progress, elements, values, options);
  457. return throwRetargetableDOMError(result);
  458. }, this._page._timeoutSettings.timeout(options));
  459. }
  460. async _selectOption(progress, elements, values, options) {
  461. const optionsToSelect = [...elements, ...values];
  462. await progress.beforeInputAction(this);
  463. return this._page._frameManager.waitForSignalsCreatedBy(progress, options.noWaitAfter, async () => {
  464. progress.throwIfAborted(); // Avoid action that has side-effects.
  465. progress.log(' selecting specified option(s)');
  466. const result = await this.evaluatePoll(progress, ([injected, node, {
  467. optionsToSelect,
  468. force
  469. }]) => {
  470. return injected.waitForElementStatesAndPerformAction(node, ['visible', 'enabled'], force, injected.selectOptions.bind(injected, optionsToSelect));
  471. }, {
  472. optionsToSelect,
  473. force: options.force
  474. });
  475. return result;
  476. });
  477. }
  478. async fill(metadata, value, options = {}) {
  479. const controller = new _progress.ProgressController(metadata, this);
  480. return controller.run(async progress => {
  481. const result = await this._fill(progress, value, options);
  482. assertDone(throwRetargetableDOMError(result));
  483. }, this._page._timeoutSettings.timeout(options));
  484. }
  485. async _fill(progress, value, options) {
  486. progress.log(`elementHandle.fill("${value}")`);
  487. await progress.beforeInputAction(this);
  488. return this._page._frameManager.waitForSignalsCreatedBy(progress, options.noWaitAfter, async () => {
  489. progress.log(' waiting for element to be visible, enabled and editable');
  490. const filled = await this.evaluatePoll(progress, ([injected, node, {
  491. value,
  492. force
  493. }]) => {
  494. return injected.waitForElementStatesAndPerformAction(node, ['visible', 'enabled', 'editable'], force, injected.fill.bind(injected, value));
  495. }, {
  496. value,
  497. force: options.force
  498. });
  499. progress.throwIfAborted(); // Avoid action that has side-effects.
  500. if (filled === 'error:notconnected') return filled;
  501. progress.log(' element is visible, enabled and editable');
  502. if (filled === 'needsinput') {
  503. progress.throwIfAborted(); // Avoid action that has side-effects.
  504. if (value) await this._page.keyboard.insertText(value);else await this._page.keyboard.press('Delete');
  505. } else {
  506. assertDone(filled);
  507. }
  508. return 'done';
  509. }, 'input');
  510. }
  511. async selectText(metadata, options = {}) {
  512. const controller = new _progress.ProgressController(metadata, this);
  513. return controller.run(async progress => {
  514. progress.throwIfAborted(); // Avoid action that has side-effects.
  515. const result = await this.evaluatePoll(progress, ([injected, node, force]) => {
  516. return injected.waitForElementStatesAndPerformAction(node, ['visible'], force, injected.selectText.bind(injected));
  517. }, options.force);
  518. assertDone(throwRetargetableDOMError(result));
  519. }, this._page._timeoutSettings.timeout(options));
  520. }
  521. async setInputFiles(metadata, params) {
  522. const inputFileItems = await (0, _fileUploadUtils.prepareFilesForUpload)(this._frame, params);
  523. const controller = new _progress.ProgressController(metadata, this);
  524. return controller.run(async progress => {
  525. const result = await this._setInputFiles(progress, inputFileItems, params);
  526. return assertDone(throwRetargetableDOMError(result));
  527. }, this._page._timeoutSettings.timeout(params));
  528. }
  529. async _setInputFiles(progress, items, options) {
  530. const {
  531. filePayloads,
  532. localPaths
  533. } = items;
  534. const multiple = filePayloads && filePayloads.length > 1 || localPaths && localPaths.length > 1;
  535. const result = await this.evaluateHandleInUtility(([injected, node, multiple]) => {
  536. const element = injected.retarget(node, 'follow-label');
  537. if (!element) return;
  538. if (element.tagName !== 'INPUT') throw injected.createStacklessError('Node is not an HTMLInputElement');
  539. if (multiple && !element.multiple) throw injected.createStacklessError('Non-multiple file input can only accept single file');
  540. return element;
  541. }, multiple);
  542. if (result === 'error:notconnected' || !result.asElement()) return 'error:notconnected';
  543. const retargeted = result.asElement();
  544. await progress.beforeInputAction(this);
  545. await this._page._frameManager.waitForSignalsCreatedBy(progress, options.noWaitAfter, async () => {
  546. progress.throwIfAborted(); // Avoid action that has side-effects.
  547. if (localPaths) await this._page._delegate.setInputFilePaths(progress, retargeted, localPaths);else await this._page._delegate.setInputFiles(retargeted, filePayloads);
  548. });
  549. return 'done';
  550. }
  551. async focus(metadata) {
  552. const controller = new _progress.ProgressController(metadata, this);
  553. await controller.run(async progress => {
  554. const result = await this._focus(progress);
  555. return assertDone(throwRetargetableDOMError(result));
  556. }, 0);
  557. }
  558. async _focus(progress, resetSelectionIfNotFocused) {
  559. progress.throwIfAborted(); // Avoid action that has side-effects.
  560. return await this.evaluateInUtility(([injected, node, resetSelectionIfNotFocused]) => injected.focusNode(node, resetSelectionIfNotFocused), resetSelectionIfNotFocused);
  561. }
  562. async _blur(progress) {
  563. progress.throwIfAborted(); // Avoid action that has side-effects.
  564. return await this.evaluateInUtility(([injected, node]) => injected.blurNode(node), {});
  565. }
  566. async type(metadata, text, options) {
  567. const controller = new _progress.ProgressController(metadata, this);
  568. return controller.run(async progress => {
  569. const result = await this._type(progress, text, options);
  570. return assertDone(throwRetargetableDOMError(result));
  571. }, this._page._timeoutSettings.timeout(options));
  572. }
  573. async _type(progress, text, options) {
  574. progress.log(`elementHandle.type("${text}")`);
  575. await progress.beforeInputAction(this);
  576. return this._page._frameManager.waitForSignalsCreatedBy(progress, options.noWaitAfter, async () => {
  577. const result = await this._focus(progress, true /* resetSelectionIfNotFocused */);
  578. if (result !== 'done') return result;
  579. progress.throwIfAborted(); // Avoid action that has side-effects.
  580. await this._page.keyboard.type(text, options);
  581. return 'done';
  582. }, 'input');
  583. }
  584. async press(metadata, key, options) {
  585. const controller = new _progress.ProgressController(metadata, this);
  586. return controller.run(async progress => {
  587. const result = await this._press(progress, key, options);
  588. return assertDone(throwRetargetableDOMError(result));
  589. }, this._page._timeoutSettings.timeout(options));
  590. }
  591. async _press(progress, key, options) {
  592. progress.log(`elementHandle.press("${key}")`);
  593. await progress.beforeInputAction(this);
  594. return this._page._frameManager.waitForSignalsCreatedBy(progress, options.noWaitAfter, async () => {
  595. const result = await this._focus(progress, true /* resetSelectionIfNotFocused */);
  596. if (result !== 'done') return result;
  597. progress.throwIfAborted(); // Avoid action that has side-effects.
  598. await this._page.keyboard.press(key, options);
  599. return 'done';
  600. }, 'input');
  601. }
  602. async check(metadata, options) {
  603. const controller = new _progress.ProgressController(metadata, this);
  604. return controller.run(async progress => {
  605. const result = await this._setChecked(progress, true, options);
  606. return assertDone(throwRetargetableDOMError(result));
  607. }, this._page._timeoutSettings.timeout(options));
  608. }
  609. async uncheck(metadata, options) {
  610. const controller = new _progress.ProgressController(metadata, this);
  611. return controller.run(async progress => {
  612. const result = await this._setChecked(progress, false, options);
  613. return assertDone(throwRetargetableDOMError(result));
  614. }, this._page._timeoutSettings.timeout(options));
  615. }
  616. async _setChecked(progress, state, options) {
  617. const isChecked = async () => {
  618. const result = await this.evaluateInUtility(([injected, node]) => injected.elementState(node, 'checked'), {});
  619. return throwRetargetableDOMError(result);
  620. };
  621. if ((await isChecked()) === state) return 'done';
  622. const result = await this._click(progress, options);
  623. if (result !== 'done') return result;
  624. if (options.trial) return 'done';
  625. if ((await isChecked()) !== state) throw new NonRecoverableDOMError('Clicking the checkbox did not change its state');
  626. return 'done';
  627. }
  628. async boundingBox() {
  629. return this._page._delegate.getBoundingBox(this);
  630. }
  631. async screenshot(metadata, options = {}) {
  632. const controller = new _progress.ProgressController(metadata, this);
  633. return controller.run(progress => this._page._screenshotter.screenshotElement(progress, this, options), this._page._timeoutSettings.timeout(options));
  634. }
  635. async querySelector(selector, options) {
  636. return this._frame.selectors.query(selector, options, this);
  637. }
  638. async querySelectorAll(selector) {
  639. return this._frame.selectors.queryAll(selector, this);
  640. }
  641. async evalOnSelector(selector, strict, expression, isFunction, arg) {
  642. return this._frame.evalOnSelector(selector, strict, expression, isFunction, arg, this);
  643. }
  644. async evalOnSelectorAll(selector, expression, isFunction, arg) {
  645. return this._frame.evalOnSelectorAll(selector, expression, isFunction, arg, this);
  646. }
  647. async isVisible(metadata) {
  648. return this._frame.isVisible(metadata, ':scope', {}, this);
  649. }
  650. async isHidden(metadata) {
  651. return this._frame.isHidden(metadata, ':scope', {}, this);
  652. }
  653. async isEnabled(metadata) {
  654. return this._frame.isEnabled(metadata, ':scope', {}, this);
  655. }
  656. async isDisabled(metadata) {
  657. return this._frame.isDisabled(metadata, ':scope', {}, this);
  658. }
  659. async isEditable(metadata) {
  660. return this._frame.isEditable(metadata, ':scope', {}, this);
  661. }
  662. async isChecked(metadata) {
  663. return this._frame.isChecked(metadata, ':scope', {}, this);
  664. }
  665. async waitForElementState(metadata, state, options = {}) {
  666. const controller = new _progress.ProgressController(metadata, this);
  667. return controller.run(async progress => {
  668. progress.log(` waiting for element to be ${state}`);
  669. const result = await this.evaluatePoll(progress, ([injected, node, state]) => {
  670. return injected.waitForElementStatesAndPerformAction(node, [state], false, () => 'done');
  671. }, state);
  672. assertDone(throwRetargetableDOMError(result));
  673. }, this._page._timeoutSettings.timeout(options));
  674. }
  675. async waitForSelector(metadata, selector, options = {}) {
  676. return this._frame.waitForSelector(metadata, selector, options, this);
  677. }
  678. async _adoptTo(context) {
  679. if (this._context !== context) {
  680. const adopted = await this._page._delegate.adoptElementHandle(this, context);
  681. this.dispose();
  682. return adopted;
  683. }
  684. return this;
  685. }
  686. async _waitForElementStates(progress, states, force) {
  687. const title = joinWithAnd(states);
  688. progress.log(` waiting for element to be ${title}`);
  689. const result = await this.evaluatePoll(progress, ([injected, node, {
  690. states,
  691. force
  692. }]) => {
  693. return injected.waitForElementStatesAndPerformAction(node, states, force, () => 'done');
  694. }, {
  695. states,
  696. force
  697. });
  698. if (result === 'error:notconnected') return result;
  699. progress.log(` element is ${title}`);
  700. return result;
  701. }
  702. async _checkFrameIsHitTarget(point) {
  703. let frame = this._frame;
  704. const data = [];
  705. while (frame.parentFrame()) {
  706. const frameElement = await frame.frameElement();
  707. const box = await frameElement.boundingBox();
  708. const style = await frameElement.evaluateInUtility(([injected, iframe]) => injected.describeIFrameStyle(iframe), {}).catch(e => 'error:notconnected');
  709. if (!box || style === 'error:notconnected') return 'error:notconnected';
  710. if (style === 'transformed') {
  711. // We cannot translate coordinates when iframe has any transform applied.
  712. // The best we can do right now is to skip the hitPoint check,
  713. // and solely rely on the event interceptor.
  714. return {
  715. framePoint: undefined
  716. };
  717. }
  718. // Translate from viewport coordinates to frame coordinates.
  719. const pointInFrame = {
  720. x: point.x - box.x - style.left,
  721. y: point.y - box.y - style.top
  722. };
  723. data.push({
  724. frame,
  725. frameElement,
  726. pointInFrame
  727. });
  728. frame = frame.parentFrame();
  729. }
  730. // Add main frame.
  731. data.push({
  732. frame,
  733. frameElement: null,
  734. pointInFrame: point
  735. });
  736. for (let i = data.length - 1; i > 0; i--) {
  737. const element = data[i - 1].frameElement;
  738. const point = data[i].pointInFrame;
  739. // Hit target in the parent frame should hit the child frame element.
  740. const hitTargetResult = await element.evaluateInUtility(([injected, element, hitPoint]) => {
  741. return injected.expectHitTarget(hitPoint, element);
  742. }, point);
  743. if (hitTargetResult !== 'done') return hitTargetResult;
  744. }
  745. return {
  746. framePoint: data[0].pointInFrame
  747. };
  748. }
  749. }
  750. // Handles an InjectedScriptPoll running in injected script:
  751. // - streams logs into progress;
  752. // - cancels the poll when progress cancels.
  753. exports.ElementHandle = ElementHandle;
  754. class InjectedScriptPollHandler {
  755. constructor(progress, poll) {
  756. this._progress = void 0;
  757. this._poll = void 0;
  758. this._progress = progress;
  759. this._poll = poll;
  760. // Ensure we cancel the poll before progress aborts and returns:
  761. // - no unnecessary work in the page;
  762. // - no possible side effects after progress promise rejects.
  763. this._progress.cleanupWhenAborted(() => this.cancel());
  764. this._streamLogs();
  765. }
  766. async _streamLogs() {
  767. while (this._poll && this._progress.isRunning()) {
  768. const log = await this._poll.evaluate(poll => poll.takeNextLogs()).catch(e => []);
  769. if (!this._poll || !this._progress.isRunning()) return;
  770. for (const entry of log) this._progress.logEntry(entry);
  771. }
  772. }
  773. async finishHandle() {
  774. try {
  775. const result = await this._poll.evaluateHandle(poll => poll.run());
  776. await this._finishInternal();
  777. return result;
  778. } finally {
  779. await this.cancel();
  780. }
  781. }
  782. async finish() {
  783. try {
  784. const result = await this._poll.evaluate(poll => poll.run());
  785. await this._finishInternal();
  786. return result;
  787. } finally {
  788. await this.cancel();
  789. }
  790. }
  791. async _finishInternal() {
  792. if (!this._poll) return;
  793. // Retrieve all the logs before continuing.
  794. const log = await this._poll.evaluate(poll => poll.takeLastLogs()).catch(e => []);
  795. for (const entry of log) this._progress.logEntry(entry);
  796. }
  797. async cancel() {
  798. if (!this._poll) return;
  799. const copy = this._poll;
  800. this._poll = null;
  801. await copy.evaluate(p => p.cancel()).catch(e => {});
  802. copy.dispose();
  803. }
  804. }
  805. exports.InjectedScriptPollHandler = InjectedScriptPollHandler;
  806. function throwRetargetableDOMError(result) {
  807. if (result === 'error:notconnected') throw new Error('Element is not attached to the DOM');
  808. return result;
  809. }
  810. function assertDone(result) {
  811. // This function converts 'done' to void and ensures typescript catches unhandled errors.
  812. }
  813. function roundPoint(point) {
  814. return {
  815. x: (point.x * 100 | 0) / 100,
  816. y: (point.y * 100 | 0) / 100
  817. };
  818. }
  819. function compensateHalfIntegerRoundingError(point) {
  820. // Firefox internally uses integer coordinates, so 8.5 is converted to 9 when clicking.
  821. //
  822. // This does not work nicely for small elements. For example, 1x1 square with corners
  823. // (8;8) and (9;9) is targeted when clicking at (8;8) but not when clicking at (9;9).
  824. // So, clicking at (8.5;8.5) will effectively click at (9;9) and miss the target.
  825. //
  826. // Therefore, we skew half-integer values from the interval (8.49, 8.51) towards
  827. // (8.47, 8.49) that is rounded towards 8. This means clicking at (8.5;8.5) will
  828. // be replaced with (8.48;8.48) and will effectively click at (8;8).
  829. //
  830. // Other browsers use float coordinates, so this change should not matter.
  831. const remainderX = point.x - Math.floor(point.x);
  832. if (remainderX > 0.49 && remainderX < 0.51) point.x -= 0.02;
  833. const remainderY = point.y - Math.floor(point.y);
  834. if (remainderY > 0.49 && remainderY < 0.51) point.y -= 0.02;
  835. }
  836. function joinWithAnd(strings) {
  837. if (strings.length <= 1) return strings.join('');
  838. return strings.slice(0, strings.length - 1).join(', ') + ' and ' + strings[strings.length - 1];
  839. }
  840. const kUnableToAdoptErrorMessage = exports.kUnableToAdoptErrorMessage = 'Unable to adopt element handle from a different document';