1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const fs = require('fs');
|
18 | const EventEmitter = require('events');
|
19 | const {helper, assert} = require('./helper');
|
20 | const {ExecutionContext, JSHandle} = require('./ExecutionContext');
|
21 | const ElementHandle = require('./ElementHandle');
|
22 |
|
23 | const readFileAsync = helper.promisify(fs.readFile);
|
24 |
|
25 | class FrameManager extends EventEmitter {
|
26 | |
27 |
|
28 |
|
29 |
|
30 |
|
31 | constructor(client, frameTree, page) {
|
32 | super();
|
33 | this._client = client;
|
34 | this._page = page;
|
35 |
|
36 | this._frames = new Map();
|
37 |
|
38 | this._contextIdToContext = new Map();
|
39 |
|
40 | this._client.on('Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId));
|
41 | this._client.on('Page.frameNavigated', event => this._onFrameNavigated(event.frame));
|
42 | this._client.on('Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url));
|
43 | this._client.on('Page.frameDetached', event => this._onFrameDetached(event.frameId));
|
44 | this._client.on('Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId));
|
45 | this._client.on('Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context));
|
46 | this._client.on('Runtime.executionContextDestroyed', event => this._onExecutionContextDestroyed(event.executionContextId));
|
47 | this._client.on('Runtime.executionContextsCleared', event => this._onExecutionContextsCleared());
|
48 | this._client.on('Page.lifecycleEvent', event => this._onLifecycleEvent(event));
|
49 |
|
50 | this._handleFrameTree(frameTree);
|
51 | }
|
52 |
|
53 | |
54 |
|
55 |
|
56 | _onLifecycleEvent(event) {
|
57 | const frame = this._frames.get(event.frameId);
|
58 | if (!frame)
|
59 | return;
|
60 | frame._onLifecycleEvent(event.loaderId, event.name);
|
61 | this.emit(FrameManager.Events.LifecycleEvent, frame);
|
62 | }
|
63 |
|
64 | |
65 |
|
66 |
|
67 | _onFrameStoppedLoading(frameId) {
|
68 | const frame = this._frames.get(frameId);
|
69 | if (!frame)
|
70 | return;
|
71 | frame._onLoadingStopped();
|
72 | this.emit(FrameManager.Events.LifecycleEvent, frame);
|
73 | }
|
74 |
|
75 | |
76 |
|
77 |
|
78 | _handleFrameTree(frameTree) {
|
79 | if (frameTree.frame.parentId)
|
80 | this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId);
|
81 | this._onFrameNavigated(frameTree.frame);
|
82 | if (!frameTree.childFrames)
|
83 | return;
|
84 |
|
85 | for (const child of frameTree.childFrames)
|
86 | this._handleFrameTree(child);
|
87 | }
|
88 |
|
89 | |
90 |
|
91 |
|
92 | mainFrame() {
|
93 | return this._mainFrame;
|
94 | }
|
95 |
|
96 | |
97 |
|
98 |
|
99 | frames() {
|
100 | return Array.from(this._frames.values());
|
101 | }
|
102 |
|
103 | |
104 |
|
105 |
|
106 |
|
107 | frame(frameId) {
|
108 | return this._frames.get(frameId) || null;
|
109 | }
|
110 |
|
111 | |
112 |
|
113 |
|
114 |
|
115 |
|
116 | _onFrameAttached(frameId, parentFrameId) {
|
117 | if (this._frames.has(frameId))
|
118 | return;
|
119 | assert(parentFrameId);
|
120 | const parentFrame = this._frames.get(parentFrameId);
|
121 | const frame = new Frame(this._client, this._page, parentFrame, frameId);
|
122 | this._frames.set(frame._id, frame);
|
123 | this.emit(FrameManager.Events.FrameAttached, frame);
|
124 | }
|
125 |
|
126 | |
127 |
|
128 |
|
129 | _onFrameNavigated(framePayload) {
|
130 | const isMainFrame = !framePayload.parentId;
|
131 | let frame = isMainFrame ? this._mainFrame : this._frames.get(framePayload.id);
|
132 | assert(isMainFrame || frame, 'We either navigate top level or have old version of the navigated frame');
|
133 |
|
134 |
|
135 | if (frame) {
|
136 | for (const child of frame.childFrames())
|
137 | this._removeFramesRecursively(child);
|
138 | }
|
139 |
|
140 |
|
141 | if (isMainFrame) {
|
142 | if (frame) {
|
143 |
|
144 | this._frames.delete(frame._id);
|
145 | frame._id = framePayload.id;
|
146 | } else {
|
147 |
|
148 | frame = new Frame(this._client, this._page, null, framePayload.id);
|
149 | }
|
150 | this._frames.set(framePayload.id, frame);
|
151 | this._mainFrame = frame;
|
152 | }
|
153 |
|
154 |
|
155 | frame._navigated(framePayload);
|
156 |
|
157 | this.emit(FrameManager.Events.FrameNavigated, frame);
|
158 | }
|
159 |
|
160 | |
161 |
|
162 |
|
163 |
|
164 | _onFrameNavigatedWithinDocument(frameId, url) {
|
165 | const frame = this._frames.get(frameId);
|
166 | if (!frame)
|
167 | return;
|
168 | frame._navigatedWithinDocument(url);
|
169 | this.emit(FrameManager.Events.FrameNavigatedWithinDocument, frame);
|
170 | this.emit(FrameManager.Events.FrameNavigated, frame);
|
171 | }
|
172 |
|
173 | |
174 |
|
175 |
|
176 | _onFrameDetached(frameId) {
|
177 | const frame = this._frames.get(frameId);
|
178 | if (frame)
|
179 | this._removeFramesRecursively(frame);
|
180 | }
|
181 |
|
182 | _onExecutionContextCreated(contextPayload) {
|
183 | const frameId = contextPayload.auxData && contextPayload.auxData.isDefault ? contextPayload.auxData.frameId : null;
|
184 | const frame = frameId ? this._frames.get(frameId) : null;
|
185 | const context = new ExecutionContext(this._client, contextPayload, this.createJSHandle.bind(this, contextPayload.id), frame);
|
186 | this._contextIdToContext.set(contextPayload.id, context);
|
187 | if (frame)
|
188 | frame._setDefaultContext(context);
|
189 | }
|
190 |
|
191 | |
192 |
|
193 |
|
194 | _removeContext(context) {
|
195 | if (context.frame())
|
196 | context.frame()._setDefaultContext(null);
|
197 | }
|
198 |
|
199 | |
200 |
|
201 |
|
202 | _onExecutionContextDestroyed(executionContextId) {
|
203 | const context = this._contextIdToContext.get(executionContextId);
|
204 | if (!context)
|
205 | return;
|
206 | this._contextIdToContext.delete(executionContextId);
|
207 | this._removeContext(context);
|
208 | }
|
209 |
|
210 | _onExecutionContextsCleared() {
|
211 | for (const context of this._contextIdToContext.values())
|
212 | this._removeContext(context);
|
213 | this._contextIdToContext.clear();
|
214 | }
|
215 |
|
216 | |
217 |
|
218 |
|
219 |
|
220 |
|
221 | createJSHandle(contextId, remoteObject) {
|
222 | const context = this._contextIdToContext.get(contextId);
|
223 | assert(context, 'INTERNAL ERROR: missing context with id = ' + contextId);
|
224 | if (remoteObject.subtype === 'node')
|
225 | return new ElementHandle(context, this._client, remoteObject, this._page, this);
|
226 | return new JSHandle(context, this._client, remoteObject);
|
227 | }
|
228 |
|
229 | |
230 |
|
231 |
|
232 | _removeFramesRecursively(frame) {
|
233 | for (const child of frame.childFrames())
|
234 | this._removeFramesRecursively(child);
|
235 | frame._detach();
|
236 | this._frames.delete(frame._id);
|
237 | this.emit(FrameManager.Events.FrameDetached, frame);
|
238 | }
|
239 | }
|
240 |
|
241 |
|
242 | FrameManager.Events = {
|
243 | FrameAttached: 'frameattached',
|
244 | FrameNavigated: 'framenavigated',
|
245 | FrameDetached: 'framedetached',
|
246 | LifecycleEvent: 'lifecycleevent',
|
247 | FrameNavigatedWithinDocument: 'framenavigatedwithindocument'
|
248 | };
|
249 |
|
250 |
|
251 |
|
252 |
|
253 | class Frame {
|
254 | |
255 |
|
256 |
|
257 |
|
258 |
|
259 | constructor(client, page, parentFrame, frameId) {
|
260 | this._client = client;
|
261 | this._page = page;
|
262 | this._parentFrame = parentFrame;
|
263 | this._url = '';
|
264 | this._id = frameId;
|
265 |
|
266 |
|
267 | this._documentPromise = null;
|
268 |
|
269 | this._contextPromise = null;
|
270 | this._contextResolveCallback = null;
|
271 | this._setDefaultContext(null);
|
272 |
|
273 |
|
274 | this._waitTasks = new Set();
|
275 | this._loaderId = '';
|
276 |
|
277 | this._lifecycleEvents = new Set();
|
278 |
|
279 |
|
280 | this._childFrames = new Set();
|
281 | if (this._parentFrame)
|
282 | this._parentFrame._childFrames.add(this);
|
283 | }
|
284 |
|
285 | |
286 |
|
287 |
|
288 | _setDefaultContext(context) {
|
289 | if (context) {
|
290 | this._contextResolveCallback.call(null, context);
|
291 | this._contextResolveCallback = null;
|
292 | for (const waitTask of this._waitTasks)
|
293 | waitTask.rerun();
|
294 | } else {
|
295 | this._documentPromise = null;
|
296 | this._contextPromise = new Promise(fulfill => {
|
297 | this._contextResolveCallback = fulfill;
|
298 | });
|
299 | }
|
300 | }
|
301 |
|
302 | |
303 |
|
304 |
|
305 | executionContext() {
|
306 | return this._contextPromise;
|
307 | }
|
308 |
|
309 | |
310 |
|
311 |
|
312 |
|
313 |
|
314 | async evaluateHandle(pageFunction, ...args) {
|
315 | const context = await this._contextPromise;
|
316 | return context.evaluateHandle(pageFunction, ...args);
|
317 | }
|
318 |
|
319 | |
320 |
|
321 |
|
322 |
|
323 |
|
324 | async evaluate(pageFunction, ...args) {
|
325 | const context = await this._contextPromise;
|
326 | return context.evaluate(pageFunction, ...args);
|
327 | }
|
328 |
|
329 | |
330 |
|
331 |
|
332 |
|
333 | async $(selector) {
|
334 | const document = await this._document();
|
335 | const value = await document.$(selector);
|
336 | return value;
|
337 | }
|
338 |
|
339 | |
340 |
|
341 |
|
342 | async _document() {
|
343 | if (this._documentPromise)
|
344 | return this._documentPromise;
|
345 | this._documentPromise = this._contextPromise.then(async context => {
|
346 | const document = await context.evaluateHandle('document');
|
347 | return document.asElement();
|
348 | });
|
349 | return this._documentPromise;
|
350 | }
|
351 |
|
352 | |
353 |
|
354 |
|
355 |
|
356 | async $x(expression) {
|
357 | const document = await this._document();
|
358 | const value = await document.$x(expression);
|
359 | return value;
|
360 | }
|
361 |
|
362 | |
363 |
|
364 |
|
365 |
|
366 |
|
367 |
|
368 | async $eval(selector, pageFunction, ...args) {
|
369 | const document = await this._document();
|
370 | return document.$eval(selector, pageFunction, ...args);
|
371 | }
|
372 |
|
373 | |
374 |
|
375 |
|
376 |
|
377 |
|
378 |
|
379 | async $$eval(selector, pageFunction, ...args) {
|
380 | const document = await this._document();
|
381 | const value = await document.$$eval(selector, pageFunction, ...args);
|
382 | return value;
|
383 | }
|
384 |
|
385 | |
386 |
|
387 |
|
388 |
|
389 | async $$(selector) {
|
390 | const document = await this._document();
|
391 | const value = await document.$$(selector);
|
392 | return value;
|
393 | }
|
394 |
|
395 | |
396 |
|
397 |
|
398 | async content() {
|
399 | return await this.evaluate(() => {
|
400 | let retVal = '';
|
401 | if (document.doctype)
|
402 | retVal = new XMLSerializer().serializeToString(document.doctype);
|
403 | if (document.documentElement)
|
404 | retVal += document.documentElement.outerHTML;
|
405 | return retVal;
|
406 | });
|
407 | }
|
408 |
|
409 | |
410 |
|
411 |
|
412 | async setContent(html) {
|
413 | await this.evaluate(html => {
|
414 | document.open();
|
415 | document.write(html);
|
416 | document.close();
|
417 | }, html);
|
418 | }
|
419 |
|
420 | |
421 |
|
422 |
|
423 | name() {
|
424 | return this._name || '';
|
425 | }
|
426 |
|
427 | |
428 |
|
429 |
|
430 | url() {
|
431 | return this._url;
|
432 | }
|
433 |
|
434 | |
435 |
|
436 |
|
437 | parentFrame() {
|
438 | return this._parentFrame;
|
439 | }
|
440 |
|
441 | |
442 |
|
443 |
|
444 | childFrames() {
|
445 | return Array.from(this._childFrames);
|
446 | }
|
447 |
|
448 | |
449 |
|
450 |
|
451 | isDetached() {
|
452 | return this._detached;
|
453 | }
|
454 |
|
455 | |
456 |
|
457 |
|
458 |
|
459 | async addScriptTag(options) {
|
460 | if (typeof options.url === 'string') {
|
461 | const url = options.url;
|
462 | try {
|
463 | const context = await this._contextPromise;
|
464 | return (await context.evaluateHandle(addScriptUrl, url, options.type)).asElement();
|
465 | } catch (error) {
|
466 | throw new Error(`Loading script from ${url} failed`);
|
467 | }
|
468 | }
|
469 |
|
470 | if (typeof options.path === 'string') {
|
471 | let contents = await readFileAsync(options.path, 'utf8');
|
472 | contents += '//# sourceURL=' + options.path.replace(/\n/g, '');
|
473 | const context = await this._contextPromise;
|
474 | return (await context.evaluateHandle(addScriptContent, contents, options.type)).asElement();
|
475 | }
|
476 |
|
477 | if (typeof options.content === 'string') {
|
478 | const context = await this._contextPromise;
|
479 | return (await context.evaluateHandle(addScriptContent, options.content, options.type)).asElement();
|
480 | }
|
481 |
|
482 | throw new Error('Provide an object with a `url`, `path` or `content` property');
|
483 |
|
484 | |
485 |
|
486 |
|
487 |
|
488 |
|
489 | async function addScriptUrl(url, type) {
|
490 | const script = document.createElement('script');
|
491 | script.src = url;
|
492 | if (type)
|
493 | script.type = type;
|
494 | const promise = new Promise((res, rej) => {
|
495 | script.onload = res;
|
496 | script.onerror = rej;
|
497 | });
|
498 | document.head.appendChild(script);
|
499 | await promise;
|
500 | return script;
|
501 | }
|
502 |
|
503 | |
504 |
|
505 |
|
506 |
|
507 |
|
508 | function addScriptContent(content, type = 'text/javascript') {
|
509 | const script = document.createElement('script');
|
510 | script.type = type;
|
511 | script.text = content;
|
512 | let error = null;
|
513 | script.onerror = e => error = e;
|
514 | document.head.appendChild(script);
|
515 | if (error)
|
516 | throw error;
|
517 | return script;
|
518 | }
|
519 | }
|
520 |
|
521 | |
522 |
|
523 |
|
524 |
|
525 | async addStyleTag(options) {
|
526 | if (typeof options.url === 'string') {
|
527 | const url = options.url;
|
528 | try {
|
529 | const context = await this._contextPromise;
|
530 | return (await context.evaluateHandle(addStyleUrl, url)).asElement();
|
531 | } catch (error) {
|
532 | throw new Error(`Loading style from ${url} failed`);
|
533 | }
|
534 | }
|
535 |
|
536 | if (typeof options.path === 'string') {
|
537 | let contents = await readFileAsync(options.path, 'utf8');
|
538 | contents += '/*# sourceURL=' + options.path.replace(/\n/g, '') + '*/';
|
539 | const context = await this._contextPromise;
|
540 | return (await context.evaluateHandle(addStyleContent, contents)).asElement();
|
541 | }
|
542 |
|
543 | if (typeof options.content === 'string') {
|
544 | const context = await this._contextPromise;
|
545 | return (await context.evaluateHandle(addStyleContent, options.content)).asElement();
|
546 | }
|
547 |
|
548 | throw new Error('Provide an object with a `url`, `path` or `content` property');
|
549 |
|
550 | |
551 |
|
552 |
|
553 |
|
554 | async function addStyleUrl(url) {
|
555 | const link = document.createElement('link');
|
556 | link.rel = 'stylesheet';
|
557 | link.href = url;
|
558 | const promise = new Promise((res, rej) => {
|
559 | link.onload = res;
|
560 | link.onerror = rej;
|
561 | });
|
562 | document.head.appendChild(link);
|
563 | await promise;
|
564 | return link;
|
565 | }
|
566 |
|
567 | |
568 |
|
569 |
|
570 |
|
571 | async function addStyleContent(content) {
|
572 | const style = document.createElement('style');
|
573 | style.type = 'text/css';
|
574 | style.appendChild(document.createTextNode(content));
|
575 | const promise = new Promise((res, rej) => {
|
576 | style.onload = res;
|
577 | style.onerror = rej;
|
578 | });
|
579 | document.head.appendChild(style);
|
580 | await promise;
|
581 | return style;
|
582 | }
|
583 | }
|
584 |
|
585 | |
586 |
|
587 |
|
588 |
|
589 | async click(selector, options = {}) {
|
590 | const handle = await this.$(selector);
|
591 | assert(handle, 'No node found for selector: ' + selector);
|
592 | await handle.click(options);
|
593 | await handle.dispose();
|
594 | }
|
595 |
|
596 | |
597 |
|
598 |
|
599 | async focus(selector) {
|
600 | const handle = await this.$(selector);
|
601 | assert(handle, 'No node found for selector: ' + selector);
|
602 | await handle.focus();
|
603 | await handle.dispose();
|
604 | }
|
605 |
|
606 | |
607 |
|
608 |
|
609 | async hover(selector) {
|
610 | const handle = await this.$(selector);
|
611 | assert(handle, 'No node found for selector: ' + selector);
|
612 | await handle.hover();
|
613 | await handle.dispose();
|
614 | }
|
615 |
|
616 | |
617 |
|
618 |
|
619 |
|
620 |
|
621 | select(selector, ...values){
|
622 | for (const value of values)
|
623 | assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"');
|
624 | return this.$eval(selector, (element, values) => {
|
625 | if (element.nodeName.toLowerCase() !== 'select')
|
626 | throw new Error('Element is not a <select> element.');
|
627 |
|
628 | const options = Array.from(element.options);
|
629 | element.value = undefined;
|
630 | for (const option of options) {
|
631 | option.selected = values.includes(option.value);
|
632 | if (option.selected && !element.multiple)
|
633 | break;
|
634 | }
|
635 | element.dispatchEvent(new Event('input', { 'bubbles': true }));
|
636 | element.dispatchEvent(new Event('change', { 'bubbles': true }));
|
637 | return options.filter(option => option.selected).map(option => option.value);
|
638 | }, values);
|
639 | }
|
640 |
|
641 | |
642 |
|
643 |
|
644 | async tap(selector) {
|
645 | const handle = await this.$(selector);
|
646 | assert(handle, 'No node found for selector: ' + selector);
|
647 | await handle.tap();
|
648 | await handle.dispose();
|
649 | }
|
650 |
|
651 | |
652 |
|
653 |
|
654 |
|
655 |
|
656 | async type(selector, text, options) {
|
657 | const handle = await this.$(selector);
|
658 | assert(handle, 'No node found for selector: ' + selector);
|
659 | await handle.type(text, options);
|
660 | await handle.dispose();
|
661 | }
|
662 |
|
663 | |
664 |
|
665 |
|
666 |
|
667 |
|
668 |
|
669 | waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
|
670 | const xPathPattern = '//';
|
671 |
|
672 | if (helper.isString(selectorOrFunctionOrTimeout)) {
|
673 | const string = (selectorOrFunctionOrTimeout);
|
674 | if (string.startsWith(xPathPattern))
|
675 | return this.waitForXPath(string, options);
|
676 | return this.waitForSelector(string, options);
|
677 | }
|
678 | if (helper.isNumber(selectorOrFunctionOrTimeout))
|
679 | return new Promise(fulfill => setTimeout(fulfill, selectorOrFunctionOrTimeout));
|
680 | if (typeof selectorOrFunctionOrTimeout === 'function')
|
681 | return this.waitForFunction(selectorOrFunctionOrTimeout, options, ...args);
|
682 | return Promise.reject(new Error('Unsupported target type: ' + (typeof selectorOrFunctionOrTimeout)));
|
683 | }
|
684 |
|
685 | |
686 |
|
687 |
|
688 |
|
689 |
|
690 | waitForSelector(selector, options = {}) {
|
691 | return this._waitForSelectorOrXPath(selector, false, options);
|
692 | }
|
693 |
|
694 | |
695 |
|
696 |
|
697 |
|
698 |
|
699 | waitForXPath(xpath, options = {}) {
|
700 | return this._waitForSelectorOrXPath(xpath, true, options);
|
701 | }
|
702 |
|
703 | |
704 |
|
705 |
|
706 |
|
707 |
|
708 | waitForFunction(pageFunction, options = {}, ...args) {
|
709 | const timeout = helper.isNumber(options.timeout) ? options.timeout : 30000;
|
710 | const polling = options.polling || 'raf';
|
711 | return new WaitTask(this, pageFunction, 'function', polling, timeout, ...args).promise;
|
712 | }
|
713 |
|
714 | |
715 |
|
716 |
|
717 | async title() {
|
718 | return this.evaluate(() => document.title);
|
719 | }
|
720 |
|
721 | |
722 |
|
723 |
|
724 |
|
725 |
|
726 |
|
727 | _waitForSelectorOrXPath(selectorOrXPath, isXPath, options = {}) {
|
728 | const waitForVisible = !!options.visible;
|
729 | const waitForHidden = !!options.hidden;
|
730 | const polling = waitForVisible || waitForHidden ? 'raf' : 'mutation';
|
731 | const timeout = helper.isNumber(options.timeout) ? options.timeout : 30000;
|
732 | return new WaitTask(this, predicate, `${isXPath ? 'XPath' : 'selector'} "${selectorOrXPath}"`, polling, timeout, selectorOrXPath, isXPath, waitForVisible, waitForHidden).promise;
|
733 |
|
734 | |
735 |
|
736 |
|
737 |
|
738 |
|
739 |
|
740 |
|
741 | function predicate(selectorOrXPath, isXPath, waitForVisible, waitForHidden) {
|
742 | const node = isXPath
|
743 | ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
|
744 | : document.querySelector(selectorOrXPath);
|
745 | if (!node)
|
746 | return waitForHidden;
|
747 | if (!waitForVisible && !waitForHidden)
|
748 | return node;
|
749 | const element = (node.nodeType === Node.TEXT_NODE ? node.parentElement : node);
|
750 |
|
751 | const style = window.getComputedStyle(element);
|
752 | const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();
|
753 | const success = (waitForVisible === isVisible || waitForHidden === !isVisible);
|
754 | return success ? node : null;
|
755 |
|
756 | |
757 |
|
758 |
|
759 | function hasVisibleBoundingBox() {
|
760 | const rect = element.getBoundingClientRect();
|
761 | return !!(rect.top || rect.bottom || rect.width || rect.height);
|
762 | }
|
763 | }
|
764 | }
|
765 |
|
766 | |
767 |
|
768 |
|
769 | _navigated(framePayload) {
|
770 | this._name = framePayload.name;
|
771 |
|
772 | this._navigationURL = framePayload.url;
|
773 | this._url = framePayload.url;
|
774 | }
|
775 |
|
776 | |
777 |
|
778 |
|
779 | _navigatedWithinDocument(url) {
|
780 | this._url = url;
|
781 | }
|
782 |
|
783 | |
784 |
|
785 |
|
786 |
|
787 | _onLifecycleEvent(loaderId, name) {
|
788 | if (name === 'init') {
|
789 | this._loaderId = loaderId;
|
790 | this._lifecycleEvents.clear();
|
791 | }
|
792 | this._lifecycleEvents.add(name);
|
793 | }
|
794 |
|
795 | _onLoadingStopped() {
|
796 | this._lifecycleEvents.add('DOMContentLoaded');
|
797 | this._lifecycleEvents.add('load');
|
798 | }
|
799 |
|
800 | _detach() {
|
801 | for (const waitTask of this._waitTasks)
|
802 | waitTask.terminate(new Error('waitForFunction failed: frame got detached.'));
|
803 | this._detached = true;
|
804 | if (this._parentFrame)
|
805 | this._parentFrame._childFrames.delete(this);
|
806 | this._parentFrame = null;
|
807 | }
|
808 | }
|
809 | helper.tracePublicAPI(Frame);
|
810 |
|
811 | class WaitTask {
|
812 | |
813 |
|
814 |
|
815 |
|
816 |
|
817 |
|
818 |
|
819 | constructor(frame, predicateBody, title, polling, timeout, ...args) {
|
820 | if (helper.isString(polling))
|
821 | assert(polling === 'raf' || polling === 'mutation', 'Unknown polling option: ' + polling);
|
822 | else if (helper.isNumber(polling))
|
823 | assert(polling > 0, 'Cannot poll with non-positive interval: ' + polling);
|
824 | else
|
825 | throw new Error('Unknown polling options: ' + polling);
|
826 |
|
827 | this._frame = frame;
|
828 | this._polling = polling;
|
829 | this._timeout = timeout;
|
830 | this._predicateBody = helper.isString(predicateBody) ? 'return ' + predicateBody : 'return (' + predicateBody + ')(...args)';
|
831 | this._args = args;
|
832 | this._runCount = 0;
|
833 | frame._waitTasks.add(this);
|
834 | this.promise = new Promise((resolve, reject) => {
|
835 | this._resolve = resolve;
|
836 | this._reject = reject;
|
837 | });
|
838 |
|
839 |
|
840 | if (timeout)
|
841 | this._timeoutTimer = setTimeout(() => this.terminate(new Error(`waiting for ${title} failed: timeout ${timeout}ms exceeded`)), timeout);
|
842 | this.rerun();
|
843 | }
|
844 |
|
845 | |
846 |
|
847 |
|
848 | terminate(error) {
|
849 | this._terminated = true;
|
850 | this._reject(error);
|
851 | this._cleanup();
|
852 | }
|
853 |
|
854 | async rerun() {
|
855 | const runCount = ++this._runCount;
|
856 |
|
857 | let success = null;
|
858 | let error = null;
|
859 | try {
|
860 | success = await (await this._frame.executionContext()).evaluateHandle(waitForPredicatePageFunction, this._predicateBody, this._polling, this._timeout, ...this._args);
|
861 | } catch (e) {
|
862 | error = e;
|
863 | }
|
864 |
|
865 | if (this._terminated || runCount !== this._runCount) {
|
866 | if (success)
|
867 | await success.dispose();
|
868 | return;
|
869 | }
|
870 |
|
871 |
|
872 | if (!error && await this._frame.evaluate(s => !s, success)) {
|
873 | await success.dispose();
|
874 | return;
|
875 | }
|
876 |
|
877 |
|
878 |
|
879 | if (error && error.message.includes('Execution context was destroyed'))
|
880 | return;
|
881 |
|
882 |
|
883 |
|
884 | if (error && error.message.includes('Cannot find context with specified id'))
|
885 | return;
|
886 |
|
887 | if (error)
|
888 | this._reject(error);
|
889 | else
|
890 | this._resolve(success);
|
891 |
|
892 | this._cleanup();
|
893 | }
|
894 |
|
895 | _cleanup() {
|
896 | clearTimeout(this._timeoutTimer);
|
897 | this._frame._waitTasks.delete(this);
|
898 | this._runningTask = null;
|
899 | }
|
900 | }
|
901 |
|
902 |
|
903 |
|
904 |
|
905 |
|
906 |
|
907 |
|
908 | async function waitForPredicatePageFunction(predicateBody, polling, timeout, ...args) {
|
909 | const predicate = new Function('...args', predicateBody);
|
910 | let timedOut = false;
|
911 | if (timeout)
|
912 | setTimeout(() => timedOut = true, timeout);
|
913 | if (polling === 'raf')
|
914 | return await pollRaf();
|
915 | if (polling === 'mutation')
|
916 | return await pollMutation();
|
917 | if (typeof polling === 'number')
|
918 | return await pollInterval(polling);
|
919 |
|
920 | |
921 |
|
922 |
|
923 | function pollMutation() {
|
924 | const success = predicate.apply(null, args);
|
925 | if (success)
|
926 | return Promise.resolve(success);
|
927 |
|
928 | let fulfill;
|
929 | const result = new Promise(x => fulfill = x);
|
930 | const observer = new MutationObserver(mutations => {
|
931 | if (timedOut) {
|
932 | observer.disconnect();
|
933 | fulfill();
|
934 | }
|
935 | const success = predicate.apply(null, args);
|
936 | if (success) {
|
937 | observer.disconnect();
|
938 | fulfill(success);
|
939 | }
|
940 | });
|
941 | observer.observe(document, {
|
942 | childList: true,
|
943 | subtree: true,
|
944 | attributes: true
|
945 | });
|
946 | return result;
|
947 | }
|
948 |
|
949 | |
950 |
|
951 |
|
952 | function pollRaf() {
|
953 | let fulfill;
|
954 | const result = new Promise(x => fulfill = x);
|
955 | onRaf();
|
956 | return result;
|
957 |
|
958 | function onRaf() {
|
959 | if (timedOut) {
|
960 | fulfill();
|
961 | return;
|
962 | }
|
963 | const success = predicate.apply(null, args);
|
964 | if (success)
|
965 | fulfill(success);
|
966 | else
|
967 | requestAnimationFrame(onRaf);
|
968 | }
|
969 | }
|
970 |
|
971 | |
972 |
|
973 |
|
974 |
|
975 | function pollInterval(pollInterval) {
|
976 | let fulfill;
|
977 | const result = new Promise(x => fulfill = x);
|
978 | onTimeout();
|
979 | return result;
|
980 |
|
981 | function onTimeout() {
|
982 | if (timedOut) {
|
983 | fulfill();
|
984 | return;
|
985 | }
|
986 | const success = predicate.apply(null, args);
|
987 | if (success)
|
988 | fulfill(success);
|
989 | else
|
990 | setTimeout(onTimeout, pollInterval);
|
991 | }
|
992 | }
|
993 | }
|
994 |
|
995 | module.exports = {FrameManager, Frame};
|