elementHandle.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var elementHandle_exports = {};
  20. __export(elementHandle_exports, {
  21. ElementHandle: () => ElementHandle,
  22. convertInputFiles: () => convertInputFiles,
  23. convertSelectOptionValues: () => convertSelectOptionValues,
  24. determineScreenshotType: () => determineScreenshotType
  25. });
  26. module.exports = __toCommonJS(elementHandle_exports);
  27. var import_frame = require("./frame");
  28. var import_jsHandle = require("./jsHandle");
  29. var import_assert = require("../utils/isomorphic/assert");
  30. var import_fileUtils = require("./fileUtils");
  31. var import_rtti = require("../utils/isomorphic/rtti");
  32. var import_writableStream = require("./writableStream");
  33. var import_mimeType = require("../utils/isomorphic/mimeType");
  34. class ElementHandle extends import_jsHandle.JSHandle {
  35. static from(handle) {
  36. return handle._object;
  37. }
  38. static fromNullable(handle) {
  39. return handle ? ElementHandle.from(handle) : null;
  40. }
  41. constructor(parent, type, guid, initializer) {
  42. super(parent, type, guid, initializer);
  43. this._frame = parent;
  44. this._elementChannel = this._channel;
  45. }
  46. asElement() {
  47. return this;
  48. }
  49. async ownerFrame() {
  50. return import_frame.Frame.fromNullable((await this._elementChannel.ownerFrame()).frame);
  51. }
  52. async contentFrame() {
  53. return import_frame.Frame.fromNullable((await this._elementChannel.contentFrame()).frame);
  54. }
  55. async getAttribute(name) {
  56. const value = (await this._elementChannel.getAttribute({ name })).value;
  57. return value === void 0 ? null : value;
  58. }
  59. async inputValue() {
  60. return (await this._elementChannel.inputValue()).value;
  61. }
  62. async textContent() {
  63. const value = (await this._elementChannel.textContent()).value;
  64. return value === void 0 ? null : value;
  65. }
  66. async innerText() {
  67. return (await this._elementChannel.innerText()).value;
  68. }
  69. async innerHTML() {
  70. return (await this._elementChannel.innerHTML()).value;
  71. }
  72. async isChecked() {
  73. return (await this._elementChannel.isChecked()).value;
  74. }
  75. async isDisabled() {
  76. return (await this._elementChannel.isDisabled()).value;
  77. }
  78. async isEditable() {
  79. return (await this._elementChannel.isEditable()).value;
  80. }
  81. async isEnabled() {
  82. return (await this._elementChannel.isEnabled()).value;
  83. }
  84. async isHidden() {
  85. return (await this._elementChannel.isHidden()).value;
  86. }
  87. async isVisible() {
  88. return (await this._elementChannel.isVisible()).value;
  89. }
  90. async dispatchEvent(type, eventInit = {}) {
  91. await this._elementChannel.dispatchEvent({ type, eventInit: (0, import_jsHandle.serializeArgument)(eventInit) });
  92. }
  93. async scrollIntoViewIfNeeded(options = {}) {
  94. await this._elementChannel.scrollIntoViewIfNeeded({ ...options, timeout: this._frame._timeout(options) });
  95. }
  96. async hover(options = {}) {
  97. await this._elementChannel.hover({ ...options, timeout: this._frame._timeout(options) });
  98. }
  99. async click(options = {}) {
  100. return await this._elementChannel.click({ ...options, timeout: this._frame._timeout(options) });
  101. }
  102. async dblclick(options = {}) {
  103. return await this._elementChannel.dblclick({ ...options, timeout: this._frame._timeout(options) });
  104. }
  105. async tap(options = {}) {
  106. return await this._elementChannel.tap({ ...options, timeout: this._frame._timeout(options) });
  107. }
  108. async selectOption(values, options = {}) {
  109. const result = await this._elementChannel.selectOption({ ...convertSelectOptionValues(values), ...options, timeout: this._frame._timeout(options) });
  110. return result.values;
  111. }
  112. async fill(value, options = {}) {
  113. return await this._elementChannel.fill({ value, ...options, timeout: this._frame._timeout(options) });
  114. }
  115. async selectText(options = {}) {
  116. await this._elementChannel.selectText({ ...options, timeout: this._frame._timeout(options) });
  117. }
  118. async setInputFiles(files, options = {}) {
  119. const frame = await this.ownerFrame();
  120. if (!frame)
  121. throw new Error("Cannot set input files to detached element");
  122. const converted = await convertInputFiles(this._platform, files, frame.page().context());
  123. await this._elementChannel.setInputFiles({ ...converted, ...options, timeout: this._frame._timeout(options) });
  124. }
  125. async focus() {
  126. await this._elementChannel.focus();
  127. }
  128. async type(text, options = {}) {
  129. await this._elementChannel.type({ text, ...options, timeout: this._frame._timeout(options) });
  130. }
  131. async press(key, options = {}) {
  132. await this._elementChannel.press({ key, ...options, timeout: this._frame._timeout(options) });
  133. }
  134. async check(options = {}) {
  135. return await this._elementChannel.check({ ...options, timeout: this._frame._timeout(options) });
  136. }
  137. async uncheck(options = {}) {
  138. return await this._elementChannel.uncheck({ ...options, timeout: this._frame._timeout(options) });
  139. }
  140. async setChecked(checked, options) {
  141. if (checked)
  142. await this.check(options);
  143. else
  144. await this.uncheck(options);
  145. }
  146. async boundingBox() {
  147. const value = (await this._elementChannel.boundingBox()).value;
  148. return value === void 0 ? null : value;
  149. }
  150. async screenshot(options = {}) {
  151. const mask = options.mask;
  152. const copy = { ...options, mask: void 0, timeout: this._frame._timeout(options) };
  153. if (!copy.type)
  154. copy.type = determineScreenshotType(options);
  155. if (mask) {
  156. copy.mask = mask.map((locator) => ({
  157. frame: locator._frame._channel,
  158. selector: locator._selector
  159. }));
  160. }
  161. const result = await this._elementChannel.screenshot(copy);
  162. if (options.path) {
  163. await (0, import_fileUtils.mkdirIfNeeded)(this._platform, options.path);
  164. await this._platform.fs().promises.writeFile(options.path, result.binary);
  165. }
  166. return result.binary;
  167. }
  168. async $(selector) {
  169. return ElementHandle.fromNullable((await this._elementChannel.querySelector({ selector })).element);
  170. }
  171. async $$(selector) {
  172. const result = await this._elementChannel.querySelectorAll({ selector });
  173. return result.elements.map((h) => ElementHandle.from(h));
  174. }
  175. async $eval(selector, pageFunction, arg) {
  176. const result = await this._elementChannel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
  177. return (0, import_jsHandle.parseResult)(result.value);
  178. }
  179. async $$eval(selector, pageFunction, arg) {
  180. const result = await this._elementChannel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
  181. return (0, import_jsHandle.parseResult)(result.value);
  182. }
  183. async waitForElementState(state, options = {}) {
  184. return await this._elementChannel.waitForElementState({ state, ...options, timeout: this._frame._timeout(options) });
  185. }
  186. async waitForSelector(selector, options = {}) {
  187. const result = await this._elementChannel.waitForSelector({ selector, ...options, timeout: this._frame._timeout(options) });
  188. return ElementHandle.fromNullable(result.element);
  189. }
  190. }
  191. function convertSelectOptionValues(values) {
  192. if (values === null)
  193. return {};
  194. if (!Array.isArray(values))
  195. values = [values];
  196. if (!values.length)
  197. return {};
  198. for (let i = 0; i < values.length; i++)
  199. (0, import_assert.assert)(values[i] !== null, `options[${i}]: expected object, got null`);
  200. if (values[0] instanceof ElementHandle)
  201. return { elements: values.map((v) => v._elementChannel) };
  202. if ((0, import_rtti.isString)(values[0]))
  203. return { options: values.map((valueOrLabel) => ({ valueOrLabel })) };
  204. return { options: values };
  205. }
  206. function filePayloadExceedsSizeLimit(payloads) {
  207. return payloads.reduce((size, item) => size + (item.buffer ? item.buffer.byteLength : 0), 0) >= import_fileUtils.fileUploadSizeLimit;
  208. }
  209. async function resolvePathsAndDirectoryForInputFiles(platform, items) {
  210. let localPaths;
  211. let localDirectory;
  212. for (const item of items) {
  213. const stat = await platform.fs().promises.stat(item);
  214. if (stat.isDirectory()) {
  215. if (localDirectory)
  216. throw new Error("Multiple directories are not supported");
  217. localDirectory = platform.path().resolve(item);
  218. } else {
  219. localPaths ??= [];
  220. localPaths.push(platform.path().resolve(item));
  221. }
  222. }
  223. if (localPaths?.length && localDirectory)
  224. throw new Error("File paths must be all files or a single directory");
  225. return [localPaths, localDirectory];
  226. }
  227. async function convertInputFiles(platform, files, context) {
  228. const items = Array.isArray(files) ? files.slice() : [files];
  229. if (items.some((item) => typeof item === "string")) {
  230. if (!items.every((item) => typeof item === "string"))
  231. throw new Error("File paths cannot be mixed with buffers");
  232. const [localPaths, localDirectory] = await resolvePathsAndDirectoryForInputFiles(platform, items);
  233. localPaths?.forEach((path) => context._checkFileAccess(path));
  234. if (localDirectory)
  235. context._checkFileAccess(localDirectory);
  236. if (context._connection.isRemote()) {
  237. const files2 = localDirectory ? (await platform.fs().promises.readdir(localDirectory, { withFileTypes: true, recursive: true })).filter((f) => f.isFile()).map((f) => platform.path().join(f.path, f.name)) : localPaths;
  238. const { writableStreams, rootDir } = await context._wrapApiCall(async () => context._channel.createTempFiles({
  239. rootDirName: localDirectory ? platform.path().basename(localDirectory) : void 0,
  240. items: await Promise.all(files2.map(async (file) => {
  241. const lastModifiedMs = (await platform.fs().promises.stat(file)).mtimeMs;
  242. return {
  243. name: localDirectory ? platform.path().relative(localDirectory, file) : platform.path().basename(file),
  244. lastModifiedMs
  245. };
  246. }))
  247. }), { internal: true });
  248. for (let i = 0; i < files2.length; i++) {
  249. const writable = import_writableStream.WritableStream.from(writableStreams[i]);
  250. await platform.streamFile(files2[i], writable.stream());
  251. }
  252. return {
  253. directoryStream: rootDir,
  254. streams: localDirectory ? void 0 : writableStreams
  255. };
  256. }
  257. return {
  258. localPaths,
  259. localDirectory
  260. };
  261. }
  262. const payloads = items;
  263. if (filePayloadExceedsSizeLimit(payloads))
  264. throw new Error("Cannot set buffer larger than 50Mb, please write it to a file and pass its path instead.");
  265. return { payloads };
  266. }
  267. function determineScreenshotType(options) {
  268. if (options.path) {
  269. const mimeType = (0, import_mimeType.getMimeTypeForPath)(options.path);
  270. if (mimeType === "image/png")
  271. return "png";
  272. else if (mimeType === "image/jpeg")
  273. return "jpeg";
  274. throw new Error(`path: unsupported mime type "${mimeType}"`);
  275. }
  276. return options.type;
  277. }
  278. // Annotate the CommonJS export names for ESM import in node:
  279. 0 && (module.exports = {
  280. ElementHandle,
  281. convertInputFiles,
  282. convertSelectOptionValues,
  283. determineScreenshotType
  284. });