/
JSHandle.js
425 lines (388 loc) · 11.7 KB
/
JSHandle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
const {assert, debugError} = require('./helper');
const path = require('path');
class JSHandle {
/**
* @param {!ExecutionContext} context
* @param {*} payload
*/
constructor(context, payload) {
this._context = context;
this._session = this._context._session;
this._executionContextId = this._context._executionContextId;
this._objectId = payload.objectId;
this._type = payload.type;
this._subtype = payload.subtype;
this._disposed = false;
this._protocolValue = {
unserializableValue: payload.unserializableValue,
value: payload.value,
objectId: payload.objectId,
};
}
/**
* @return {ExecutionContext}
*/
executionContext() {
return this._context;
}
/**
* @override
* @return {string}
*/
toString() {
if (this._objectId)
return 'JSHandle@' + (this._subtype || this._type);
return 'JSHandle:' + this._deserializeValue(this._protocolValue);
}
/**
* @param {string} propertyName
* @return {!Promise<?JSHandle>}
*/
async getProperty(propertyName) {
const objectHandle = await this._context.evaluateHandle((object, propertyName) => {
const result = {__proto__: null};
result[propertyName] = object[propertyName];
return result;
}, this, propertyName);
const properties = await objectHandle.getProperties();
const result = properties.get(propertyName) || null;
await objectHandle.dispose();
return result;
}
/**
* @return {!Promise<Map<string, !JSHandle>>}
*/
async getProperties() {
const response = await this._session.send('Page.getObjectProperties', {
executionContextId: this._executionContextId,
objectId: this._objectId,
});
const result = new Map();
for (const property of response.properties) {
result.set(property.name, createHandle(this._context, property.value, null));
}
return result;
}
_deserializeValue({unserializableValue, value}) {
if (unserializableValue === 'Infinity')
return Infinity;
if (unserializableValue === '-Infinity')
return -Infinity;
if (unserializableValue === '-0')
return -0;
if (unserializableValue === 'NaN')
return NaN;
return value;
}
async jsonValue() {
if (!this._objectId)
return this._deserializeValue(this._protocolValue);
const simpleValue = await this._session.send('Page.evaluate', {
executionContextId: this._executionContextId,
returnByValue: true,
functionText: (e => e).toString(),
args: [this._protocolValue],
});
return this._deserializeValue(simpleValue.result);
}
/**
* @return {?ElementHandle}
*/
asElement() {
return null;
}
async dispose() {
if (!this._objectId)
return;
this._disposed = true;
await this._session.send('Page.disposeObject', {
executionContextId: this._executionContextId,
objectId: this._objectId,
});
}
}
class ElementHandle extends JSHandle {
/**
* @param {Frame} frame
* @param {ExecutionContext} context
* @param {*} payload
*/
constructor(frame, context, payload) {
super(context, payload);
this._frame = frame;
this._frameId = frame._frameId;
}
/**
* @return {?Frame}
*/
async contentFrame() {
const {frameId} = await this._session.send('Page.contentFrame', {
frameId: this._frameId,
objectId: this._objectId,
});
if (!frameId)
return null;
const frame = this._frame._frameManager.frame(frameId);
return frame;
}
/**
* @override
* @return {!ElementHandle}
*/
asElement() {
return this;
}
/**
* @return {!Promise<{width: number, height: number, x: number, y: number}>}
*/
async boundingBox() {
return await this._session.send('Page.getBoundingBox', {
frameId: this._frameId,
objectId: this._objectId,
});
}
/**
* @param {{encoding?: string, path?: string}} options
*/
async screenshot(options = {}) {
const clip = await this._session.send('Page.getBoundingBox', {
frameId: this._frameId,
objectId: this._objectId,
});
if (!clip)
throw new Error('Node is either not visible or not an HTMLElement');
assert(clip.width, 'Node has 0 width.');
assert(clip.height, 'Node has 0 height.');
await this._scrollIntoViewIfNeeded();
return await this._frame._page.screenshot(Object.assign({}, options, {
clip: {
x: clip.x,
y: clip.y,
width: clip.width,
height: clip.height,
},
}));
}
/**
* @returns {!Promise<boolean>}
*/
isIntersectingViewport() {
return this._frame.evaluate(async element => {
const visibleRatio = await new Promise(resolve => {
const observer = new IntersectionObserver(entries => {
resolve(entries[0].intersectionRatio);
observer.disconnect();
});
observer.observe(element);
// Firefox doesn't call IntersectionObserver callback unless
// there are rafs.
requestAnimationFrame(() => {});
});
return visibleRatio > 0;
}, this);
}
/**
* @param {string} selector
* @return {!Promise<?ElementHandle>}
*/
async $(selector) {
const handle = await this._frame.evaluateHandle(
(element, selector) => element.querySelector(selector),
this, selector
);
const element = handle.asElement();
if (element)
return element;
await handle.dispose();
return null;
}
/**
* @param {string} selector
* @return {!Promise<!Array<!ElementHandle>>}
*/
async $$(selector) {
const arrayHandle = await this._frame.evaluateHandle(
(element, selector) => element.querySelectorAll(selector),
this, selector
);
const properties = await arrayHandle.getProperties();
await arrayHandle.dispose();
const result = [];
for (const property of properties.values()) {
const elementHandle = property.asElement();
if (elementHandle)
result.push(elementHandle);
}
return result;
}
/**
* @param {string} selector
* @param {Function|String} pageFunction
* @param {!Array<*>} args
* @return {!Promise<(!Object|undefined)>}
*/
async $eval(selector, pageFunction, ...args) {
const elementHandle = await this.$(selector);
if (!elementHandle)
throw new Error(`Error: failed to find element matching selector "${selector}"`);
const result = await this._frame.evaluate(pageFunction, elementHandle, ...args);
await elementHandle.dispose();
return result;
}
/**
* @param {string} selector
* @param {Function|String} pageFunction
* @param {!Array<*>} args
* @return {!Promise<(!Object|undefined)>}
*/
async $$eval(selector, pageFunction, ...args) {
const arrayHandle = await this._frame.evaluateHandle(
(element, selector) => Array.from(element.querySelectorAll(selector)),
this, selector
);
const result = await this._frame.evaluate(pageFunction, arrayHandle, ...args);
await arrayHandle.dispose();
return result;
}
/**
* @param {string} expression
* @return {!Promise<!Array<!ElementHandle>>}
*/
async $x(expression) {
const arrayHandle = await this._frame.evaluateHandle(
(element, expression) => {
const document = element.ownerDocument || element;
const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);
const array = [];
let item;
while ((item = iterator.iterateNext()))
array.push(item);
return array;
},
this, expression
);
const properties = await arrayHandle.getProperties();
await arrayHandle.dispose();
const result = [];
for (const property of properties.values()) {
const elementHandle = property.asElement();
if (elementHandle)
result.push(elementHandle);
}
return result;
}
async _scrollIntoViewIfNeeded() {
const error = await this._frame.evaluate(async(element) => {
if (!element.isConnected)
return 'Node is detached from document';
if (element.nodeType !== Node.ELEMENT_NODE)
return 'Node is not of type HTMLElement';
const visibleRatio = await new Promise(resolve => {
const observer = new IntersectionObserver(entries => {
resolve(entries[0].intersectionRatio);
observer.disconnect();
});
observer.observe(element);
// Firefox doesn't call IntersectionObserver callback unless
// there are rafs.
requestAnimationFrame(() => {});
});
if (visibleRatio !== 1.0)
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});
return false;
}, this);
if (error)
throw new Error(error);
}
/**
* @param {!{delay?: number, button?: string, clickCount?: number}=} options
*/
async click(options) {
await this._scrollIntoViewIfNeeded();
const {x, y} = await this._clickablePoint();
await this._frame._page.mouse.click(x, y, options);
}
/**
* @param {!Array<string>} filePaths
*/
async uploadFile(...filePaths) {
const files = filePaths.map(filePath => path.resolve(filePath));
await this._session.send('Page.setFileInputFiles', {
frameId: this._frameId,
objectId: this._objectId,
files,
});
}
async hover() {
await this._scrollIntoViewIfNeeded();
const {x, y} = await this._clickablePoint();
await this._frame._page.mouse.move(x, y);
}
async focus() {
await this._frame.evaluate(element => element.focus(), this);
}
/**
* @param {string} text
* @param {{delay: (number|undefined)}=} options
*/
async type(text, options) {
await this.focus();
await this._frame._page.keyboard.type(text, options);
}
/**
* @param {string} key
* @param {!{delay?: number}=} options
*/
async press(key, options) {
await this.focus();
await this._frame._page.keyboard.press(key, options);
}
/**
* @return {!Promise<!{x: number, y: number}>}
*/
async _clickablePoint() {
const result = await this._session.send('Page.getContentQuads', {
frameId: this._frameId,
objectId: this._objectId,
}).catch(debugError);
if (!result || !result.quads.length)
throw new Error('Node is either not visible or not an HTMLElement');
// Filter out quads that have too small area to click into.
const quads = result.quads.filter(quad => computeQuadArea(quad) > 1);
if (!quads.length)
throw new Error('Node is either not visible or not an HTMLElement');
// Return the middle point of the first quad.
return computeQuadCenter(quads[0]);
}
}
function createHandle(context, result, exceptionDetails) {
const frame = context.frame();
if (exceptionDetails) {
if (exceptionDetails.value)
throw new Error('Evaluation failed: ' + JSON.stringify(exceptionDetails.value));
else
throw new Error('Evaluation failed: ' + exceptionDetails.text + '\n' + exceptionDetails.stack);
}
return result.subtype === 'node' ? new ElementHandle(frame, context, result) : new JSHandle(context, result);
}
function computeQuadArea(quad) {
// Compute sum of all directed areas of adjacent triangles
// https://en.wikipedia.org/wiki/Polygon#Simple_polygons
let area = 0;
const points = [quad.p1, quad.p2, quad.p3, quad.p4];
for (let i = 0; i < points.length; ++i) {
const p1 = points[i];
const p2 = points[(i + 1) % points.length];
area += (p1.x * p2.y - p2.x * p1.y) / 2;
}
return Math.abs(area);
}
function computeQuadCenter(quad) {
let x = 0, y = 0;
for (const point of [quad.p1, quad.p2, quad.p3, quad.p4]) {
x += point.x;
y += point.y;
}
return {x: x / 4, y: y / 4};
}
module.exports = {JSHandle, ElementHandle, createHandle};