const {helper, assert} = require('./helper'); const {TimeoutError} = require('./Errors'); const fs = require('fs'); const util = require('util'); const EventEmitter = require('events'); const {Events} = require('./Events'); const {ExecutionContext} = require('./ExecutionContext'); const {NavigationWatchdog, NextNavigationWatchdog} = require('./NavigationWatchdog'); const readFileAsync = util.promisify(fs.readFile); class FrameManager extends EventEmitter { /** * @param {PageSession} session * @param {Page} page */ constructor(session, page, networkManager, timeoutSettings) { super(); this._session = session; this._page = page; this._networkManager = networkManager; this._timeoutSettings = timeoutSettings; this._mainFrame = null; this._frames = new Map(); this._eventListeners = [ helper.addEventListener(this._session, 'Page.eventFired', this._onEventFired.bind(this)), helper.addEventListener(this._session, 'Page.frameAttached', this._onFrameAttached.bind(this)), helper.addEventListener(this._session, 'Page.frameDetached', this._onFrameDetached.bind(this)), helper.addEventListener(this._session, 'Page.navigationCommitted', this._onNavigationCommitted.bind(this)), helper.addEventListener(this._session, 'Page.sameDocumentNavigation', this._onSameDocumentNavigation.bind(this)), ]; } frame(frameId) { return this._frames.get(frameId); } mainFrame() { return this._mainFrame; } frames() { /** @type {!Array} */ let frames = []; collect(this._mainFrame); return frames; function collect(frame) { frames.push(frame); for (const subframe of frame._children) collect(subframe); } } _onNavigationCommitted(params) { const frame = this._frames.get(params.frameId); frame._navigated(params.url, params.name, params.navigationId); frame._DOMContentLoadedFired = false; frame._loadFired = false; this.emit(Events.FrameManager.FrameNavigated, frame); } _onSameDocumentNavigation(params) { const frame = this._frames.get(params.frameId); frame._url = params.url; this.emit(Events.FrameManager.FrameNavigated, frame); } _onFrameAttached(params) { const frame = new Frame(this._session, this, this._networkManager, this._page, params.frameId, this._timeoutSettings); const parentFrame = this._frames.get(params.parentFrameId) || null; if (parentFrame) { frame._parentFrame = parentFrame; parentFrame._children.add(frame); } else { assert(!this._mainFrame, 'INTERNAL ERROR: re-attaching main frame!'); this._mainFrame = frame; } this._frames.set(params.frameId, frame); this.emit(Events.FrameManager.FrameAttached, frame); } _onFrameDetached(params) { const frame = this._frames.get(params.frameId); this._frames.delete(params.frameId); frame._detach(); this.emit(Events.FrameManager.FrameDetached, frame); } _onEventFired({frameId, name}) { const frame = this._frames.get(frameId); frame._firedEvents.add(name.toLowerCase()); if (frame === this._mainFrame) { if (name === 'load') this.emit(Events.FrameManager.Load); else if (name === 'DOMContentLoaded') this.emit(Events.FrameManager.DOMContentLoaded); } } dispose() { helper.removeEventListeners(this._eventListeners); } } class Frame { /** * @param {*} session * @param {!Page} page * @param {string} frameId */ constructor(session, frameManager, networkManager, page, frameId, timeoutSettings) { this._session = session; this._page = page; this._frameManager = frameManager; this._networkManager = networkManager; this._timeoutSettings = timeoutSettings; this._frameId = frameId; /** @type {?Frame} */ this._parentFrame = null; this._url = ''; this._name = ''; /** @type {!Set} */ this._children = new Set(); this._isDetached = false; this._firedEvents = new Set(); /** @type {!Set} */ this._waitTasks = new Set(); this._documentPromise = null; this._executionContext = new ExecutionContext(this._session, this, this._frameId); } async executionContext() { return this._executionContext; } /** * @param {!{timeout?: number, waitUntil?: string|!Array}} options */ async waitForNavigation(options = {}) { const { timeout = this._timeoutSettings.navigationTimeout(), waitUntil = ['load'], } = options; const normalizedWaitUntil = normalizeWaitUntil(waitUntil); const timeoutError = new TimeoutError('Navigation Timeout Exceeded: ' + timeout + 'ms'); let timeoutCallback; const timeoutPromise = new Promise(resolve => timeoutCallback = resolve.bind(null, timeoutError)); const timeoutId = timeout ? setTimeout(timeoutCallback, timeout) : null; const nextNavigationDog = new NextNavigationWatchdog(this._session, this); const error1 = await Promise.race([ nextNavigationDog.promise(), timeoutPromise, ]); nextNavigationDog.dispose(); // If timeout happened first - throw. if (error1) { clearTimeout(timeoutId); throw error1; } const {navigationId, url} = nextNavigationDog.navigation(); if (!navigationId) { // Same document navigation happened. clearTimeout(timeoutId); return null; } const watchDog = new NavigationWatchdog(this._session, this, this._networkManager, navigationId, url, normalizedWaitUntil); const error = await Promise.race([ timeoutPromise, watchDog.promise(), ]); watchDog.dispose(); clearTimeout(timeoutId); if (error) throw error; return watchDog.navigationResponse(); } /** * @param {string} url * @param {!{timeout?: number, waitUntil?: string|!Array}} options */ async goto(url, options = {}) { const { timeout = this._timeoutSettings.navigationTimeout(), waitUntil = ['load'], referer, } = options; const normalizedWaitUntil = normalizeWaitUntil(waitUntil); const {navigationId} = await this._session.send('Page.navigate', { frameId: this._frameId, referer, url, }); if (!navigationId) return; const timeoutError = new TimeoutError('Navigation Timeout Exceeded: ' + timeout + 'ms'); let timeoutCallback; const timeoutPromise = new Promise(resolve => timeoutCallback = resolve.bind(null, timeoutError)); const timeoutId = timeout ? setTimeout(timeoutCallback, timeout) : null; const watchDog = new NavigationWatchdog(this._session, this, this._networkManager, navigationId, url, normalizedWaitUntil); const error = await Promise.race([ timeoutPromise, watchDog.promise(), ]); watchDog.dispose(); clearTimeout(timeoutId); if (error) throw error; return watchDog.navigationResponse(); } /** * @param {string} selector * @param {!{delay?: number, button?: string, clickCount?: number}=} options */ async click(selector, options = {}) { const handle = await this.$(selector); assert(handle, 'No node found for selector: ' + selector); await handle.click(options); await handle.dispose(); } /** * @param {string} selector * @param {string} text * @param {{delay: (number|undefined)}=} options */ async type(selector, text, options) { const handle = await this.$(selector); assert(handle, 'No node found for selector: ' + selector); await handle.type(text, options); await handle.dispose(); } /** * @param {string} selector */ async focus(selector) { const handle = await this.$(selector); assert(handle, 'No node found for selector: ' + selector); await handle.focus(); await handle.dispose(); } /** * @param {string} selector */ async hover(selector) { const handle = await this.$(selector); assert(handle, 'No node found for selector: ' + selector); await handle.hover(); await handle.dispose(); } _detach() { this._parentFrame._children.delete(this); this._parentFrame = null; this._isDetached = true; for (const waitTask of this._waitTasks) waitTask.terminate(new Error('waitForFunction failed: frame got detached.')); } _navigated(url, name, navigationId) { this._url = url; this._name = name; this._lastCommittedNavigationId = navigationId; this._documentPromise = null; this._firedEvents.clear(); } /** * @param {string} selector * @param {!Array} values * @return {!Promise>} */ select(selector, ...values) { for (const value of values) assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"'); return this.$eval(selector, (element, values) => { if (element.nodeName.toLowerCase() !== 'select') throw new Error('Element is not a