/** * 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} = require('./helper'); const {ExecutionContext, JSHandle} = require('./ExecutionContext'); const ElementHandle = require('./ElementHandle'); const readFileAsync = helper.promisify(fs.readFile); class FrameManager extends EventEmitter { /** * @param {!Puppeteer.Session} client * @param {{frame: Object, childFrames: ?Array}} frameTree * @param {!Puppeteer.Page} page */ constructor(client, frameTree, page) { super(); this._client = client; this._page = page; /** @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.frameDetached', event => this._onFrameDetached(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 {!Object} 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 {{frame: Object, childFrames: ?Array}} 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 {!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 * @return {?Frame} */ _onFrameAttached(frameId, parentFrameId) { if (this._frames.has(frameId)) return; console.assert(parentFrameId); const parentFrame = this._frames.get(parentFrameId); const frame = new Frame(this._client, this._page, parentFrame, frameId); this._frames.set(frame._id, frame); this.emit(FrameManager.Events.FrameAttached, frame); } /** * @param {!Object} framePayload */ _onFrameNavigated(framePayload) { const isMainFrame = !framePayload.parentId; let frame = isMainFrame ? this._mainFrame : this._frames.get(framePayload.id); console.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._client, this._page, 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 */ _onFrameDetached(frameId) { const frame = this._frames.get(frameId); if (frame) this._removeFramesRecursively(frame); } _onExecutionContextCreated(contextPayload) { const context = new ExecutionContext(this._client, contextPayload, this.createJSHandle.bind(this, contextPayload.id)); this._contextIdToContext.set(contextPayload.id, context); const frame = context._frameId ? this._frames.get(context._frameId) : null; if (frame && context._isDefault) frame._setDefaultContext(context); } /** * @param {!ExecutionContext} context */ _removeContext(context) { const frame = context._frameId ? this._frames.get(context._frameId) : null; if (frame && context._isDefault) frame._setDefaultContext(null); } /** * @param {string} executionContextId */ _onExecutionContextDestroyed(executionContextId) { const context = this._contextIdToContext.get(executionContextId); if (!context) return; this._contextIdToContext.delete(executionContextId); this._removeContext(context); } _onExecutionContextsCleared() { for (const context of this._contextIdToContext.values()) this._removeContext(context); this._contextIdToContext.clear(); } /** * @param {string} contextId * @param {*} remoteObject * @return {!JSHandle} */ createJSHandle(contextId, remoteObject) { const context = this._contextIdToContext.get(contextId); console.assert(context, 'INTERNAL ERROR: missing context with id = ' + contextId); if (remoteObject.subtype === 'node') return new ElementHandle(context, this._client, remoteObject, this._page); return new JSHandle(context, this._client, remoteObject); } /** * @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' }; /** * @unrestricted */ class Frame { /** * @param {!Puppeteer.Session} client * @param {?Frame} parentFrame * @param {string} frameId */ constructor(client, page, parentFrame, frameId) { this._client = client; this._page = page; this._parentFrame = parentFrame; this._url = ''; this._id = frameId; /** @type {?Promise} */ this._documentPromise = null; /** @type {?Promise} */ this._contextPromise = null; 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 */ _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; }); } } /** * @return {!Promise} */ executionContext() { return this._contextPromise; } /** * @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 elementHandle = await this.$(selector); if (!elementHandle) throw new Error(`Error: failed to find element matching selector "${selector}"`); const result = await this.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 context = await this._contextPromise; const arrayHandle = await context.evaluateHandle(selector => Array.from(document.querySelectorAll(selector)), selector); const result = await this.evaluate(pageFunction, arrayHandle, ...args); await arrayHandle.dispose(); return result; } /** * @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)).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)).asElement(); } if (typeof options.content === 'string') { const context = await this._contextPromise; return (await context.evaluateHandle(addScriptContent, options.content)).asElement(); } throw new Error('Provide an object with a `url`, `path` or `content` property'); /** * @param {string} url * @return {!Promise} */ async function addScriptUrl(url) { const script = document.createElement('script'); script.src = url; document.head.appendChild(script); await new Promise((res, rej) => { script.onload = res; script.onerror = rej; }); return script; } /** * @param {string} content * @return {!HTMLElement} */ function addScriptContent(content) { const script = document.createElement('script'); script.type = 'text/javascript'; script.text = content; document.head.appendChild(script); 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; document.head.appendChild(link); await new Promise((res, rej) => { link.onload = res; link.onerror = rej; }); return link; } /** * @param {string} content * @return {!HTMLElement} */ function addStyleContent(content) { const style = document.createElement('style'); style.type = 'text/css'; style.appendChild(document.createTextNode(content)); document.head.appendChild(style); return style; } } /** * @param {string} selector * @param {!Array} values * @return {!Promise>} */ async select(selector, ...values){ for (const value of values) console.assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"'); return await this.$eval(selector, (element, values) => { if (element.nodeName.toLowerCase() !== 'select') throw new Error('Element is not a