/** * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const fs = require('fs'); const EventEmitter = require('events'); const {helper, assert} = require('./helper'); const {ExecutionContext} = require('./ExecutionContext'); const {TimeoutError} = require('./Errors'); const {NetworkManager} = require('./NetworkManager'); const {Connection} = require('./Connection'); const readFileAsync = helper.promisify(fs.readFile); class FrameManager extends EventEmitter { /** * @param {!Puppeteer.CDPSession} client * @param {!Protocol.Page.FrameTree} frameTree * @param {!Puppeteer.Page} page * @param {!Puppeteer.NetworkManager} networkManager */ constructor(client, frameTree, page, networkManager) { super(); this._client = client; this._page = page; this._networkManager = networkManager; this._defaultNavigationTimeout = 30000; /** @type {!Map} */ this._frames = new Map(); /** @type {!Map} */ this._contextIdToContext = new Map(); this._client.on('Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)); this._client.on('Page.frameNavigated', event => this._onFrameNavigated(event.frame)); this._client.on('Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)); this._client.on('Page.frameDetached', event => this._onFrameDetached(event.frameId)); this._client.on('Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)); this._client.on('Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)); this._client.on('Runtime.executionContextDestroyed', event => this._onExecutionContextDestroyed(event.executionContextId)); this._client.on('Runtime.executionContextsCleared', event => this._onExecutionContextsCleared()); this._client.on('Page.lifecycleEvent', event => this._onLifecycleEvent(event)); this._handleFrameTree(frameTree); } /** * @param {number} timeout */ setDefaultNavigationTimeout(timeout) { this._defaultNavigationTimeout = timeout; } /** * @param {!Puppeteer.Frame} frame * @param {string} url * @param {!Object=} options * @return {!Promise} */ async navigateFrame(frame, url, options = {}) { const referrer = typeof options.referer === 'string' ? options.referer : this._networkManager.extraHTTPHeaders()['referer']; const timeout = typeof options.timeout === 'number' ? options.timeout : this._defaultNavigationTimeout; const watcher = new NavigatorWatcher(this._client, this, this._networkManager, frame, timeout, options); let ensureNewDocumentNavigation = false; let error = await Promise.race([ navigate(this._client, url, referrer, frame._id), watcher.timeoutOrTerminationPromise(), ]); if (!error) { error = await Promise.race([ watcher.timeoutOrTerminationPromise(), ensureNewDocumentNavigation ? watcher.newDocumentNavigationPromise() : watcher.sameDocumentNavigationPromise(), ]); } watcher.dispose(); if (error) throw error; return watcher.navigationResponse(); /** * @param {!Puppeteer.CDPSession} client * @param {string} url * @param {string} referrer * @param {string} frameId * @return {!Promise} */ async function navigate(client, url, referrer, frameId) { try { const response = await client.send('Page.navigate', {url, referrer, frameId}); ensureNewDocumentNavigation = !!response.loaderId; return response.errorText ? new Error(`${response.errorText} at ${url}`) : null; } catch (error) { return error; } } } /** * @param {!Puppeteer.Frame} frame * @param {!Object=} options * @return {!Promise} */ async waitForFrameNavigation(frame, options) { const timeout = typeof options.timeout === 'number' ? options.timeout : this._defaultNavigationTimeout; const watcher = new NavigatorWatcher(this._client, this, this._networkManager, frame, timeout, options); const error = await Promise.race([ watcher.timeoutOrTerminationPromise(), watcher.sameDocumentNavigationPromise(), watcher.newDocumentNavigationPromise() ]); watcher.dispose(); if (error) throw error; return watcher.navigationResponse(); } /** * @param {!Protocol.Page.lifecycleEventPayload} event */ _onLifecycleEvent(event) { const frame = this._frames.get(event.frameId); if (!frame) return; frame._onLifecycleEvent(event.loaderId, event.name); this.emit(FrameManager.Events.LifecycleEvent, frame); } /** * @param {string} frameId */ _onFrameStoppedLoading(frameId) { const frame = this._frames.get(frameId); if (!frame) return; frame._onLoadingStopped(); this.emit(FrameManager.Events.LifecycleEvent, frame); } /** * @param {!Protocol.Page.FrameTree} frameTree */ _handleFrameTree(frameTree) { if (frameTree.frame.parentId) this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId); this._onFrameNavigated(frameTree.frame); if (!frameTree.childFrames) return; for (const child of frameTree.childFrames) this._handleFrameTree(child); } /** * @return {!Puppeteer.Page} */ page() { return this._page; } /** * @return {!Frame} */ mainFrame() { return this._mainFrame; } /** * @return {!Array} */ frames() { return Array.from(this._frames.values()); } /** * @param {!string} frameId * @return {?Frame} */ frame(frameId) { return this._frames.get(frameId) || null; } /** * @param {string} frameId * @param {?string} parentFrameId */ _onFrameAttached(frameId, parentFrameId) { if (this._frames.has(frameId)) return; assert(parentFrameId); const parentFrame = this._frames.get(parentFrameId); const frame = new Frame(this, this._client, parentFrame, frameId); this._frames.set(frame._id, frame); this.emit(FrameManager.Events.FrameAttached, frame); } /** * @param {!Protocol.Page.Frame} framePayload */ _onFrameNavigated(framePayload) { const isMainFrame = !framePayload.parentId; let frame = isMainFrame ? this._mainFrame : this._frames.get(framePayload.id); assert(isMainFrame || frame, 'We either navigate top level or have old version of the navigated frame'); // Detach all child frames first. if (frame) { for (const child of frame.childFrames()) this._removeFramesRecursively(child); } // Update or create main frame. if (isMainFrame) { if (frame) { // Update frame id to retain frame identity on cross-process navigation. this._frames.delete(frame._id); frame._id = framePayload.id; } else { // Initial main frame navigation. frame = new Frame(this, this._client, null, framePayload.id); } this._frames.set(framePayload.id, frame); this._mainFrame = frame; } // Update frame payload. frame._navigated(framePayload); this.emit(FrameManager.Events.FrameNavigated, frame); } /** * @param {string} frameId * @param {string} url */ _onFrameNavigatedWithinDocument(frameId, url) { const frame = this._frames.get(frameId); if (!frame) return; frame._navigatedWithinDocument(url); this.emit(FrameManager.Events.FrameNavigatedWithinDocument, frame); this.emit(FrameManager.Events.FrameNavigated, frame); } /** * @param {string} frameId */ _onFrameDetached(frameId) { const frame = this._frames.get(frameId); if (frame) this._removeFramesRecursively(frame); } _onExecutionContextCreated(contextPayload) { const frameId = contextPayload.auxData ? contextPayload.auxData.frameId : null; const frame = this._frames.get(frameId) || null; /** @type {!ExecutionContext} */ const context = new ExecutionContext(this._client, contextPayload, frame); this._contextIdToContext.set(contextPayload.id, context); if (frame) frame._addExecutionContext(context); } /** * @param {number} executionContextId */ _onExecutionContextDestroyed(executionContextId) { const context = this._contextIdToContext.get(executionContextId); if (!context) return; this._contextIdToContext.delete(executionContextId); if (context.frame()) context.frame()._removeExecutionContext(context); } _onExecutionContextsCleared() { for (const context of this._contextIdToContext.values()) { if (context.frame()) context.frame()._removeExecutionContext(context); } this._contextIdToContext.clear(); } /** * @param {number} contextId * @return {!ExecutionContext} */ executionContextById(contextId) { const context = this._contextIdToContext.get(contextId); assert(context, 'INTERNAL ERROR: missing context with id = ' + contextId); return context; } /** * @param {!Frame} frame */ _removeFramesRecursively(frame) { for (const child of frame.childFrames()) this._removeFramesRecursively(child); frame._detach(); this._frames.delete(frame._id); this.emit(FrameManager.Events.FrameDetached, frame); } } /** @enum {string} */ FrameManager.Events = { FrameAttached: 'frameattached', FrameNavigated: 'framenavigated', FrameDetached: 'framedetached', LifecycleEvent: 'lifecycleevent', FrameNavigatedWithinDocument: 'framenavigatedwithindocument', ExecutionContextCreated: 'executioncontextcreated', ExecutionContextDestroyed: 'executioncontextdestroyed', }; /** * @unrestricted */ class Frame { /** * @param {!FrameManager} frameManager * @param {!Puppeteer.CDPSession} client * @param {?Frame} parentFrame * @param {string} frameId */ constructor(frameManager, client, parentFrame, frameId) { this._frameManager = frameManager; this._client = client; this._parentFrame = parentFrame; this._url = ''; this._id = frameId; this._detached = false; /** @type {?Promise} */ this._documentPromise = null; /** @type {!Promise} */ this._contextPromise; this._contextResolveCallback = null; this._setDefaultContext(null); /** @type {!Set} */ this._waitTasks = new Set(); this._loaderId = ''; /** @type {!Set} */ this._lifecycleEvents = new Set(); /** @type {!Set} */ this._childFrames = new Set(); if (this._parentFrame) this._parentFrame._childFrames.add(this); } /** * @param {!ExecutionContext} context */ _addExecutionContext(context) { if (context._isDefault) this._setDefaultContext(context); } /** * @param {!ExecutionContext} context */ _removeExecutionContext(context) { if (context._isDefault) this._setDefaultContext(null); } /** * @param {?ExecutionContext} context */ _setDefaultContext(context) { if (context) { this._contextResolveCallback.call(null, context); this._contextResolveCallback = null; for (const waitTask of this._waitTasks) waitTask.rerun(); } else { this._documentPromise = null; this._contextPromise = new Promise(fulfill => { this._contextResolveCallback = fulfill; }); } } /** * @param {string} url * @param {!Object=} options * @return {!Promise} */ async goto(url, options = {}) { return await this._frameManager.navigateFrame(this, url, options); } /** * @param {!Object=} options * @return {!Promise} */ async waitForNavigation(options = {}) { return await this._frameManager.waitForFrameNavigation(this, options); } /** * @return {!Promise} */ executionContext() { return this._contextPromise; } /** * @param {function()|string} pageFunction * @param {!Array<*>} args * @return {!Promise} */ async evaluateHandle(pageFunction, ...args) { const context = await this._contextPromise; return context.evaluateHandle(pageFunction, ...args); } /** * @param {Function|string} pageFunction * @param {!Array<*>} args * @return {!Promise<*>} */ async evaluate(pageFunction, ...args) { const context = await this._contextPromise; return context.evaluate(pageFunction, ...args); } /** * @param {string} selector * @return {!Promise} */ async $(selector) { const document = await this._document(); const value = await document.$(selector); return value; } /** * @return {!Promise} */ async _document() { if (this._documentPromise) return this._documentPromise; this._documentPromise = this._contextPromise.then(async context => { const document = await context.evaluateHandle('document'); return document.asElement(); }); return this._documentPromise; } /** * @param {string} expression * @return {!Promise>} */ async $x(expression) { const document = await this._document(); const value = await document.$x(expression); return value; } /** * @param {string} selector * @param {Function|string} pageFunction * @param {!Array<*>} args * @return {!Promise<(!Object|undefined)>} */ async $eval(selector, pageFunction, ...args) { const document = await this._document(); return document.$eval(selector, pageFunction, ...args); } /** * @param {string} selector * @param {Function|string} pageFunction * @param {!Array<*>} args * @return {!Promise<(!Object|undefined)>} */ async $$eval(selector, pageFunction, ...args) { const document = await this._document(); const value = await document.$$eval(selector, pageFunction, ...args); return value; } /** * @param {string} selector * @return {!Promise>} */ async $$(selector) { const document = await this._document(); const value = await document.$$(selector); return value; } /** * @return {!Promise} */ async content() { return await this.evaluate(() => { let retVal = ''; if (document.doctype) retVal = new XMLSerializer().serializeToString(document.doctype); if (document.documentElement) retVal += document.documentElement.outerHTML; return retVal; }); } /** * @param {string} html */ async setContent(html) { await this.evaluate(html => { document.open(); document.write(html); document.close(); }, html); } /** * @return {string} */ name() { return this._name || ''; } /** * @return {string} */ url() { return this._url; } /** * @return {?Frame} */ parentFrame() { return this._parentFrame; } /** * @return {!Array.} */ childFrames() { return Array.from(this._childFrames); } /** * @return {boolean} */ isDetached() { return this._detached; } /** * @param {Object} options * @return {!Promise} */ async addScriptTag(options) { if (typeof options.url === 'string') { const url = options.url; try { const context = await this._contextPromise; return (await context.evaluateHandle(addScriptUrl, url, options.type)).asElement(); } catch (error) { throw new Error(`Loading script from ${url} failed`); } } if (typeof options.path === 'string') { let contents = await readFileAsync(options.path, 'utf8'); contents += '//# sourceURL=' + options.path.replace(/\n/g, ''); const context = await this._contextPromise; return (await context.evaluateHandle(addScriptContent, contents, options.type)).asElement(); } if (typeof options.content === 'string') { const context = await this._contextPromise; return (await context.evaluateHandle(addScriptContent, options.content, options.type)).asElement(); } throw new Error('Provide an object with a `url`, `path` or `content` property'); /** * @param {string} url * @param {string} type * @return {!Promise} */ async function addScriptUrl(url, type) { const script = document.createElement('script'); script.src = url; if (type) script.type = type; const promise = new Promise((res, rej) => { script.onload = res; script.onerror = rej; }); document.head.appendChild(script); await promise; return script; } /** * @param {string} content * @param {string} type * @return {!HTMLElement} */ function addScriptContent(content, type = 'text/javascript') { const script = document.createElement('script'); script.type = type; script.text = content; let error = null; script.onerror = e => error = e; document.head.appendChild(script); if (error) throw error; return script; } } /** * @param {Object} options * @return {!Promise} */ async addStyleTag(options) { if (typeof options.url === 'string') { const url = options.url; try { const context = await this._contextPromise; return (await context.evaluateHandle(addStyleUrl, url)).asElement(); } catch (error) { throw new Error(`Loading style from ${url} failed`); } } if (typeof options.path === 'string') { let contents = await readFileAsync(options.path, 'utf8'); contents += '/*# sourceURL=' + options.path.replace(/\n/g, '') + '*/'; const context = await this._contextPromise; return (await context.evaluateHandle(addStyleContent, contents)).asElement(); } if (typeof options.content === 'string') { const context = await this._contextPromise; return (await context.evaluateHandle(addStyleContent, options.content)).asElement(); } throw new Error('Provide an object with a `url`, `path` or `content` property'); /** * @param {string} url * @return {!Promise} */ async function addStyleUrl(url) { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = url; const promise = new Promise((res, rej) => { link.onload = res; link.onerror = rej; }); document.head.appendChild(link); await promise; return link; } /** * @param {string} content * @return {!Promise} */ async function addStyleContent(content) { const style = document.createElement('style'); style.type = 'text/css'; style.appendChild(document.createTextNode(content)); const promise = new Promise((res, rej) => { style.onload = res; style.onerror = rej; }); document.head.appendChild(style); await promise; return style; } } /** * @param {string} selector * @param {!Object=} 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 */ 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(); } /** * @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