const {helper, assert} = require('./helper'); const {TimeoutError} = require('./Errors'); const fs = require('fs'); const util = require('util'); const readFileAsync = util.promisify(fs.readFile); class DOMWorld { constructor(frame, timeoutSettings) { this._frame = frame; this._timeoutSettings = timeoutSettings; this._documentPromise = null; this._contextPromise; this._contextResolveCallback = null; this._setContext(null); /** @type {!Set} */ this._waitTasks = new Set(); this._detached = false; } frame() { return this._frame; } _setContext(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; }); } } _detach() { this._detached = true; for (const waitTask of this._waitTasks) waitTask.terminate(new Error('waitForFunction failed: frame got detached.')); } async executionContext() { if (this._detached) throw new Error(`Execution Context is not available in detached frame "${this.url()}" (are you trying to evaluate?)`); return this._contextPromise; } async evaluateHandle(pageFunction, ...args) { const context = await this.executionContext(); return context.evaluateHandle(pageFunction, ...args); } async evaluate(pageFunction, ...args) { const context = await this.executionContext(); return context.evaluate(pageFunction, ...args); } /** * @param {string} selector * @return {!Promise} */ async $(selector) { const document = await this._document(); return document.$(selector); } _document() { if (!this._documentPromise) this._documentPromise = this.evaluateHandle('document').then(handle => handle.asElement()); return this._documentPromise; } /** * @param {string} expression * @return {!Promise>} */ async $x(expression) { const document = await this._document(); return document.$x(expression); } /** * @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(); return document.$$eval(selector, pageFunction, ...args); } /** * @param {string} selector * @return {!Promise>} */ async $$(selector) { const document = await this._document(); return document.$$(selector); } /** * @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); } /** * @param {!{content?: string, path?: string, type?: string, url?: string}} options * @return {!Promise} */ async addScriptTag(options) { if (typeof options.url === 'string') { const url = options.url; try { return (await this.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, ''); return (await this.evaluateHandle(addScriptContent, contents, options.type)).asElement(); } if (typeof options.content === 'string') { return (await this.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 {!{content?: string, path?: string, url?: string}} options * @return {!Promise} */ async addStyleTag(options) { if (typeof options.url === 'string') { const url = options.url; try { return (await this.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, '') + '*/'; return (await this.evaluateHandle(addStyleContent, contents)).asElement(); } if (typeof options.content === 'string') { return (await this.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 {!{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 */ 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