puppeteer-core
Advanced tools
Comparing version 1.7.0 to 1.8.0
10
index.js
@@ -25,5 +25,7 @@ /** | ||
// If node does not support async await, use the compiled version. | ||
if (asyncawait) | ||
module.exports = require('./lib/Puppeteer'); | ||
else | ||
module.exports = require('./node6/lib/Puppeteer'); | ||
const Puppeteer = asyncawait ? require('./lib/Puppeteer') : require('./node6/lib/Puppeteer'); | ||
const packageJson = require('./package.json'); | ||
const preferredRevision = packageJson.puppeteer.chromium_revision; | ||
const isPuppeteerCore = packageJson.name === 'puppeteer-core'; | ||
module.exports = new Puppeteer(__dirname, preferredRevision, isPuppeteerCore); |
@@ -40,7 +40,7 @@ /** | ||
this._defaultContext = new BrowserContext(this, null); | ||
this._defaultContext = new BrowserContext(this._connection, this, null); | ||
/** @type {Map<string, BrowserContext>} */ | ||
this._contexts = new Map(); | ||
for (const contextId of contextIds) | ||
this._contexts.set(contextId, new BrowserContext(this, contextId)); | ||
this._contexts.set(contextId, new BrowserContext(this._connection, this, contextId)); | ||
@@ -69,3 +69,3 @@ /** @type {Map<string, Target>} */ | ||
const {browserContextId} = await this._connection.send('Target.createBrowserContext'); | ||
const context = new BrowserContext(this, browserContextId); | ||
const context = new BrowserContext(this._connection, this, browserContextId); | ||
this._contexts.set(browserContextId, context); | ||
@@ -83,2 +83,9 @@ return context; | ||
/** | ||
* @return {!BrowserContext} | ||
*/ | ||
defaultBrowserContext() { | ||
return this._defaultContext; | ||
} | ||
/** | ||
* @param {?string} contextId | ||
@@ -167,3 +174,3 @@ */ | ||
/** | ||
* @param {string} contextId | ||
* @param {?string} contextId | ||
* @return {!Promise<!Puppeteer.Page>} | ||
@@ -238,7 +245,9 @@ */ | ||
/** | ||
* @param {!Puppeteer.Connection} connection | ||
* @param {!Browser} browser | ||
* @param {?string} contextId | ||
*/ | ||
constructor(browser, contextId) { | ||
constructor(connection, browser, contextId) { | ||
super(); | ||
this._connection = connection; | ||
this._browser = browser; | ||
@@ -275,2 +284,39 @@ this._id = contextId; | ||
/** | ||
* @param {string} origin | ||
* @param {!Array<string>} permissions | ||
*/ | ||
async overridePermissions(origin, permissions) { | ||
const webPermissionToProtocol = new Map([ | ||
['geolocation', 'geolocation'], | ||
['midi', 'midi'], | ||
['notifications', 'notifications'], | ||
['push', 'push'], | ||
['camera', 'videoCapture'], | ||
['microphone', 'audioCapture'], | ||
['background-sync', 'backgroundSync'], | ||
['ambient-light-sensor', 'sensors'], | ||
['accelerometer', 'sensors'], | ||
['gyroscope', 'sensors'], | ||
['magnetometer', 'sensors'], | ||
['accessibility-events', 'accessibilityEvents'], | ||
['clipboard-read', 'clipboardRead'], | ||
['clipboard-write', 'clipboardWrite'], | ||
['payment-handler', 'paymentHandler'], | ||
// chrome-specific permissions we have. | ||
['midi-sysex', 'midiSysex'], | ||
]); | ||
permissions = permissions.map(permission => { | ||
const protocolPermission = webPermissionToProtocol.get(permission); | ||
if (!protocolPermission) | ||
throw new Error('Unknown permission: ' + permission); | ||
return protocolPermission; | ||
}); | ||
await this._connection.send('Browser.grantPermissions', {origin, browserContextId: this._id || undefined, permissions}); | ||
} | ||
async clearPermissionOverrides() { | ||
await this._connection.send('Browser.resetPermissions', {browserContextId: this._id || undefined}); | ||
} | ||
/** | ||
* @return {!Promise<!Puppeteer.Page>} | ||
@@ -277,0 +323,0 @@ */ |
@@ -52,6 +52,7 @@ /** | ||
/** | ||
* @param {string} projectRoot | ||
* @param {!BrowserFetcher.Options=} options | ||
*/ | ||
constructor(options = {}) { | ||
this._downloadsFolder = options.path || path.join(helper.projectRoot(), '.local-chromium'); | ||
constructor(projectRoot, options = {}) { | ||
this._downloadsFolder = options.path || path.join(projectRoot, '.local-chromium'); | ||
this._downloadHost = options.host || DEFAULT_DOWNLOAD_HOST; | ||
@@ -260,4 +261,3 @@ this._platform = options.platform || ''; | ||
const driver = options.protocol === 'https:' ? 'https' : 'http'; | ||
const request = require(driver).request(options, res => { | ||
const requestCallback = res => { | ||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) | ||
@@ -267,3 +267,6 @@ httpRequest(res.headers.location, method, response); | ||
response(res); | ||
}); | ||
}; | ||
const request = options.protocol === 'https:' ? | ||
require('https').request(options, requestCallback) : | ||
require('http').request(options, requestCallback); | ||
request.end(); | ||
@@ -270,0 +273,0 @@ return request; |
@@ -175,2 +175,3 @@ /** | ||
this._callbacks = new Map(); | ||
/** @type {null|Connection|CDPSession} */ | ||
this._connection = connection; | ||
@@ -238,2 +239,4 @@ this._targetType = targetType; | ||
async detach() { | ||
if (!this._connection) | ||
throw new Error(`Session already detached. Most likely the ${this._targetType} has been closed.`); | ||
await this._connection.send('Target.detachFromTarget', {sessionId: this._sessionId}); | ||
@@ -271,4 +274,3 @@ } | ||
message += ` ${object.error.data}`; | ||
if (object.error.message) | ||
return rewriteError(error, message); | ||
return rewriteError(error, message); | ||
} | ||
@@ -275,0 +277,0 @@ |
@@ -17,3 +17,4 @@ /** | ||
const {helper, assert} = require('./helper'); | ||
const {helper, assert, debugError} = require('./helper'); | ||
const path = require('path'); | ||
@@ -23,2 +24,11 @@ const EVALUATION_SCRIPT_URL = '__puppeteer_evaluation_script__'; | ||
function createJSHandle(context, remoteObject) { | ||
const frame = context.frame(); | ||
if (remoteObject.subtype === 'node' && frame) { | ||
const frameManager = frame._frameManager; | ||
return new ElementHandle(context, context._client, remoteObject, frameManager.page(), frameManager); | ||
} | ||
return new JSHandle(context, context._client, remoteObject); | ||
} | ||
class ExecutionContext { | ||
@@ -28,6 +38,5 @@ /** | ||
* @param {!Protocol.Runtime.ExecutionContextDescription} contextPayload | ||
* @param {function(!Protocol.Runtime.RemoteObject):!JSHandle} objectHandleFactory | ||
* @param {?Puppeteer.Frame} frame | ||
*/ | ||
constructor(client, contextPayload, objectHandleFactory, frame) { | ||
constructor(client, contextPayload, frame) { | ||
this._client = client; | ||
@@ -37,3 +46,2 @@ this._frame = frame; | ||
this._isDefault = contextPayload.auxData ? !!contextPayload.auxData['isDefault'] : false; | ||
this._objectHandleFactory = objectHandleFactory; | ||
} | ||
@@ -87,3 +95,3 @@ | ||
throw new Error('Evaluation failed: ' + helper.getExceptionMessage(exceptionDetails)); | ||
return this._objectHandleFactory(remoteObject); | ||
return createJSHandle(this, remoteObject); | ||
} | ||
@@ -104,3 +112,3 @@ | ||
throw new Error('Evaluation failed: ' + helper.getExceptionMessage(exceptionDetails)); | ||
return this._objectHandleFactory(remoteObject); | ||
return createJSHandle(this, remoteObject); | ||
@@ -157,3 +165,3 @@ /** | ||
}); | ||
return this._objectHandleFactory(response.objects); | ||
return createJSHandle(this, response.objects); | ||
} | ||
@@ -210,3 +218,3 @@ } | ||
continue; | ||
result.set(property.name, this._context._objectHandleFactory(property.value)); | ||
result.set(property.name, createJSHandle(this._context, property.value)); | ||
} | ||
@@ -259,3 +267,379 @@ return result; | ||
class ElementHandle extends JSHandle { | ||
/** | ||
* @param {!Puppeteer.ExecutionContext} context | ||
* @param {!Puppeteer.CDPSession} client | ||
* @param {!Protocol.Runtime.RemoteObject} remoteObject | ||
* @param {!Puppeteer.Page} page | ||
* @param {!Puppeteer.FrameManager} frameManager | ||
*/ | ||
constructor(context, client, remoteObject, page, frameManager) { | ||
super(context, client, remoteObject); | ||
this._client = client; | ||
this._remoteObject = remoteObject; | ||
this._page = page; | ||
this._frameManager = frameManager; | ||
this._disposed = false; | ||
} | ||
/** | ||
* @override | ||
* @return {?ElementHandle} | ||
*/ | ||
asElement() { | ||
return this; | ||
} | ||
/** | ||
* @return {!Promise<?Puppeteer.Frame>} | ||
*/ | ||
async contentFrame() { | ||
const nodeInfo = await this._client.send('DOM.describeNode', { | ||
objectId: this._remoteObject.objectId | ||
}); | ||
if (typeof nodeInfo.node.frameId !== 'string') | ||
return null; | ||
return this._frameManager.frame(nodeInfo.node.frameId); | ||
} | ||
async _scrollIntoViewIfNeeded() { | ||
const error = await this.executionContext().evaluate(async(element, pageJavascriptEnabled) => { | ||
if (!element.isConnected) | ||
return 'Node is detached from document'; | ||
if (element.nodeType !== Node.ELEMENT_NODE) | ||
return 'Node is not of type HTMLElement'; | ||
// force-scroll if page's javascript is disabled. | ||
if (!pageJavascriptEnabled) { | ||
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'}); | ||
return false; | ||
} | ||
const visibleRatio = await new Promise(resolve => { | ||
const observer = new IntersectionObserver(entries => { | ||
resolve(entries[0].intersectionRatio); | ||
observer.disconnect(); | ||
}); | ||
observer.observe(element); | ||
}); | ||
if (visibleRatio !== 1.0) | ||
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'}); | ||
return false; | ||
}, this, this._page._javascriptEnabled); | ||
if (error) | ||
throw new Error(error); | ||
} | ||
/** | ||
* @return {!Promise<!{x: number, y: number}>} | ||
*/ | ||
async _clickablePoint() { | ||
const result = await this._client.send('DOM.getContentQuads', { | ||
objectId: this._remoteObject.objectId | ||
}).catch(debugError); | ||
if (!result || !result.quads.length) | ||
throw new Error('Node is either not visible or not an HTMLElement'); | ||
// Filter out quads that have too small area to click into. | ||
const quads = result.quads.map(quad => this._fromProtocolQuad(quad)).filter(quad => computeQuadArea(quad) > 1); | ||
if (!quads.length) | ||
throw new Error('Node is either not visible or not an HTMLElement'); | ||
// Return the middle point of the first quad. | ||
const quad = quads[0]; | ||
let x = 0; | ||
let y = 0; | ||
for (const point of quad) { | ||
x += point.x; | ||
y += point.y; | ||
} | ||
return { | ||
x: x / 4, | ||
y: y / 4 | ||
}; | ||
} | ||
/** | ||
* @return {!Promise<void|Protocol.DOM.getBoxModelReturnValue>} | ||
*/ | ||
_getBoxModel() { | ||
return this._client.send('DOM.getBoxModel', { | ||
objectId: this._remoteObject.objectId | ||
}).catch(error => debugError(error)); | ||
} | ||
/** | ||
* @param {!Array<number>} quad | ||
* @return {!Array<object>} | ||
*/ | ||
_fromProtocolQuad(quad) { | ||
return [ | ||
{x: quad[0], y: quad[1]}, | ||
{x: quad[2], y: quad[3]}, | ||
{x: quad[4], y: quad[5]}, | ||
{x: quad[6], y: quad[7]} | ||
]; | ||
} | ||
async hover() { | ||
await this._scrollIntoViewIfNeeded(); | ||
const {x, y} = await this._clickablePoint(); | ||
await this._page.mouse.move(x, y); | ||
} | ||
/** | ||
* @param {!Object=} options | ||
*/ | ||
async click(options = {}) { | ||
await this._scrollIntoViewIfNeeded(); | ||
const {x, y} = await this._clickablePoint(); | ||
await this._page.mouse.click(x, y, options); | ||
} | ||
/** | ||
* @param {!Array<string>} filePaths | ||
* @return {!Promise} | ||
*/ | ||
async uploadFile(...filePaths) { | ||
const files = filePaths.map(filePath => path.resolve(filePath)); | ||
const objectId = this._remoteObject.objectId; | ||
return this._client.send('DOM.setFileInputFiles', { objectId, files }); | ||
} | ||
async tap() { | ||
await this._scrollIntoViewIfNeeded(); | ||
const {x, y} = await this._clickablePoint(); | ||
await this._page.touchscreen.tap(x, y); | ||
} | ||
async focus() { | ||
await this.executionContext().evaluate(element => element.focus(), this); | ||
} | ||
/** | ||
* @param {string} text | ||
* @param {{delay: (number|undefined)}=} options | ||
*/ | ||
async type(text, options) { | ||
await this.focus(); | ||
await this._page.keyboard.type(text, options); | ||
} | ||
/** | ||
* @param {string} key | ||
* @param {!Object=} options | ||
*/ | ||
async press(key, options) { | ||
await this.focus(); | ||
await this._page.keyboard.press(key, options); | ||
} | ||
/** | ||
* @return {!Promise<?{x: number, y: number, width: number, height: number}>} | ||
*/ | ||
async boundingBox() { | ||
const result = await this._getBoxModel(); | ||
if (!result) | ||
return null; | ||
const quad = result.model.border; | ||
const x = Math.min(quad[0], quad[2], quad[4], quad[6]); | ||
const y = Math.min(quad[1], quad[3], quad[5], quad[7]); | ||
const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x; | ||
const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y; | ||
return {x, y, width, height}; | ||
} | ||
/** | ||
* @return {!Promise<?object>} | ||
*/ | ||
async boxModel() { | ||
const result = await this._getBoxModel(); | ||
if (!result) | ||
return null; | ||
const {content, padding, border, margin, width, height} = result.model; | ||
return { | ||
content: this._fromProtocolQuad(content), | ||
padding: this._fromProtocolQuad(padding), | ||
border: this._fromProtocolQuad(border), | ||
margin: this._fromProtocolQuad(margin), | ||
width, | ||
height | ||
}; | ||
} | ||
/** | ||
* | ||
* @param {!Object=} options | ||
* @returns {!Promise<Object>} | ||
*/ | ||
async screenshot(options = {}) { | ||
let needsViewportReset = false; | ||
let boundingBox = await this.boundingBox(); | ||
assert(boundingBox, 'Node is either not visible or not an HTMLElement'); | ||
const viewport = this._page.viewport(); | ||
if (viewport && (boundingBox.width > viewport.width || boundingBox.height > viewport.height)) { | ||
const newViewport = { | ||
width: Math.max(viewport.width, Math.ceil(boundingBox.width)), | ||
height: Math.max(viewport.height, Math.ceil(boundingBox.height)), | ||
}; | ||
await this._page.setViewport(Object.assign({}, viewport, newViewport)); | ||
needsViewportReset = true; | ||
} | ||
await this._scrollIntoViewIfNeeded(); | ||
boundingBox = await this.boundingBox(); | ||
assert(boundingBox, 'Node is either not visible or not an HTMLElement'); | ||
const { layoutViewport: { pageX, pageY } } = await this._client.send('Page.getLayoutMetrics'); | ||
const clip = Object.assign({}, boundingBox); | ||
clip.x += pageX; | ||
clip.y += pageY; | ||
const imageData = await this._page.screenshot(Object.assign({}, { | ||
clip | ||
}, options)); | ||
if (needsViewportReset) | ||
await this._page.setViewport(viewport); | ||
return imageData; | ||
} | ||
/** | ||
* @param {string} selector | ||
* @return {!Promise<?ElementHandle>} | ||
*/ | ||
async $(selector) { | ||
const handle = await this.executionContext().evaluateHandle( | ||
(element, selector) => element.querySelector(selector), | ||
this, selector | ||
); | ||
const element = handle.asElement(); | ||
if (element) | ||
return element; | ||
await handle.dispose(); | ||
return null; | ||
} | ||
/** | ||
* @param {string} selector | ||
* @return {!Promise<!Array<!ElementHandle>>} | ||
*/ | ||
async $$(selector) { | ||
const arrayHandle = await this.executionContext().evaluateHandle( | ||
(element, selector) => element.querySelectorAll(selector), | ||
this, selector | ||
); | ||
const properties = await arrayHandle.getProperties(); | ||
await arrayHandle.dispose(); | ||
const result = []; | ||
for (const property of properties.values()) { | ||
const elementHandle = property.asElement(); | ||
if (elementHandle) | ||
result.push(elementHandle); | ||
} | ||
return result; | ||
} | ||
/** | ||
* @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.executionContext().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 arrayHandle = await this.executionContext().evaluateHandle( | ||
(element, selector) => Array.from(element.querySelectorAll(selector)), | ||
this, selector | ||
); | ||
const result = await this.executionContext().evaluate(pageFunction, arrayHandle, ...args); | ||
await arrayHandle.dispose(); | ||
return result; | ||
} | ||
/** | ||
* @param {string} expression | ||
* @return {!Promise<!Array<!ElementHandle>>} | ||
*/ | ||
async $x(expression) { | ||
const arrayHandle = await this.executionContext().evaluateHandle( | ||
(element, expression) => { | ||
const document = element.ownerDocument || element; | ||
const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE); | ||
const array = []; | ||
let item; | ||
while ((item = iterator.iterateNext())) | ||
array.push(item); | ||
return array; | ||
}, | ||
this, expression | ||
); | ||
const properties = await arrayHandle.getProperties(); | ||
await arrayHandle.dispose(); | ||
const result = []; | ||
for (const property of properties.values()) { | ||
const elementHandle = property.asElement(); | ||
if (elementHandle) | ||
result.push(elementHandle); | ||
} | ||
return result; | ||
} | ||
/** | ||
* @returns {!Promise<boolean>} | ||
*/ | ||
isIntersectingViewport() { | ||
return this.executionContext().evaluate(async element => { | ||
const visibleRatio = await new Promise(resolve => { | ||
const observer = new IntersectionObserver(entries => { | ||
resolve(entries[0].intersectionRatio); | ||
observer.disconnect(); | ||
}); | ||
observer.observe(element); | ||
}); | ||
return visibleRatio > 0; | ||
}, this); | ||
} | ||
} | ||
function computeQuadArea(quad) { | ||
// Compute sum of all directed areas of adjacent triangles | ||
// https://en.wikipedia.org/wiki/Polygon#Simple_polygons | ||
let area = 0; | ||
for (let i = 0; i < quad.length; ++i) { | ||
const p1 = quad[i]; | ||
const p2 = quad[(i + 1) % quad.length]; | ||
area += (p1.x * p2.y - p2.x * p1.y) / 2; | ||
} | ||
return area; | ||
} | ||
helper.tracePublicAPI(ElementHandle); | ||
helper.tracePublicAPI(JSHandle); | ||
module.exports = {ExecutionContext, JSHandle, EVALUATION_SCRIPT_URL}; | ||
helper.tracePublicAPI(ExecutionContext); | ||
module.exports = {ExecutionContext, JSHandle, ElementHandle, createJSHandle, EVALUATION_SCRIPT_URL}; |
@@ -20,4 +20,3 @@ /** | ||
const {helper, assert} = require('./helper'); | ||
const {ExecutionContext, JSHandle} = require('./ExecutionContext'); | ||
const {ElementHandle} = require('./ElementHandle'); | ||
const {ExecutionContext} = require('./ExecutionContext'); | ||
const {TimeoutError} = require('./Errors'); | ||
@@ -92,2 +91,9 @@ | ||
/** | ||
* @return {!Puppeteer.Page} | ||
*/ | ||
page() { | ||
return this._page; | ||
} | ||
/** | ||
* @return {!Frame} | ||
@@ -117,3 +123,2 @@ */ | ||
* @param {?string} parentFrameId | ||
* @return {?Frame} | ||
*/ | ||
@@ -125,3 +130,3 @@ _onFrameAttached(frameId, parentFrameId) { | ||
const parentFrame = this._frames.get(parentFrameId); | ||
const frame = new Frame(this._client, parentFrame, frameId); | ||
const frame = new Frame(this, this._client, parentFrame, frameId); | ||
this._frames.set(frame._id, frame); | ||
@@ -153,3 +158,3 @@ this.emit(FrameManager.Events.FrameAttached, frame); | ||
// Initial main frame navigation. | ||
frame = new Frame(this._client, null, framePayload.id); | ||
frame = new Frame(this, this._client, null, framePayload.id); | ||
} | ||
@@ -192,3 +197,3 @@ this._frames.set(framePayload.id, frame); | ||
/** @type {!ExecutionContext} */ | ||
const context = new ExecutionContext(this._client, contextPayload, obj => this.createJSHandle(context, obj), frame); | ||
const context = new ExecutionContext(this._client, contextPayload, frame); | ||
this._contextIdToContext.set(contextPayload.id, context); | ||
@@ -230,13 +235,2 @@ if (frame) | ||
/** | ||
* @param {!ExecutionContext} context | ||
* @param {!Protocol.Runtime.RemoteObject} remoteObject | ||
* @return {!JSHandle} | ||
*/ | ||
createJSHandle(context, remoteObject) { | ||
if (remoteObject.subtype === 'node') | ||
return new ElementHandle(context, this._client, remoteObject, this._page, this); | ||
return new JSHandle(context, this._client, remoteObject); | ||
} | ||
/** | ||
* @param {!Frame} frame | ||
@@ -269,2 +263,3 @@ */ | ||
/** | ||
* @param {!FrameManager} frameManager | ||
* @param {!Puppeteer.CDPSession} client | ||
@@ -274,3 +269,4 @@ * @param {?Frame} parentFrame | ||
*/ | ||
constructor(client, parentFrame, frameId) { | ||
constructor(frameManager, client, parentFrame, frameId) { | ||
this._frameManager = frameManager; | ||
this._client = client; | ||
@@ -280,10 +276,12 @@ this._parentFrame = parentFrame; | ||
this._id = frameId; | ||
this._detached = false; | ||
/** @type {?Promise<!ElementHandle>} */ | ||
/** @type {?Promise<!Puppeteer.ElementHandle>} */ | ||
this._documentPromise = null; | ||
/** @type {?Promise<!ExecutionContext>} */ | ||
this._contextPromise = null; | ||
/** @type {!Promise<!ExecutionContext>} */ | ||
this._contextPromise; | ||
this._contextResolveCallback = null; | ||
this._setDefaultContext(null); | ||
/** @type {!Set<!WaitTask>} */ | ||
@@ -363,3 +361,3 @@ this._waitTasks = new Set(); | ||
* @param {string} selector | ||
* @return {!Promise<?ElementHandle>} | ||
* @return {!Promise<?Puppeteer.ElementHandle>} | ||
*/ | ||
@@ -373,3 +371,3 @@ async $(selector) { | ||
/** | ||
* @return {!Promise<!ElementHandle>} | ||
* @return {!Promise<!Puppeteer.ElementHandle>} | ||
*/ | ||
@@ -388,3 +386,3 @@ async _document() { | ||
* @param {string} expression | ||
* @return {!Promise<!Array<!ElementHandle>>} | ||
* @return {!Promise<!Array<!Puppeteer.ElementHandle>>} | ||
*/ | ||
@@ -422,3 +420,3 @@ async $x(expression) { | ||
* @param {string} selector | ||
* @return {!Promise<!Array<!ElementHandle>>} | ||
* @return {!Promise<!Array<!Puppeteer.ElementHandle>>} | ||
*/ | ||
@@ -493,3 +491,3 @@ async $$(selector) { | ||
* @param {Object} options | ||
* @return {!Promise<!ElementHandle>} | ||
* @return {!Promise<!Puppeteer.ElementHandle>} | ||
*/ | ||
@@ -560,3 +558,3 @@ async addScriptTag(options) { | ||
* @param {Object} options | ||
* @return {!Promise<!ElementHandle>} | ||
* @return {!Promise<!Puppeteer.ElementHandle>} | ||
*/ | ||
@@ -897,3 +895,3 @@ async addStyleTag(options) { | ||
const runCount = ++this._runCount; | ||
/** @type {?JSHandle} */ | ||
/** @type {?Puppeteer.JSHandle} */ | ||
let success = null; | ||
@@ -900,0 +898,0 @@ let error = null; |
@@ -16,4 +16,2 @@ /** | ||
*/ | ||
const fs = require('fs'); | ||
const path = require('path'); | ||
const {TimeoutError} = require('./Errors'); | ||
@@ -24,3 +22,3 @@ | ||
let apiCoverage = null; | ||
let projectRoot = null; | ||
class Helper { | ||
@@ -51,13 +49,2 @@ /** | ||
/** | ||
* @return {string} | ||
*/ | ||
static projectRoot() { | ||
if (!projectRoot) { | ||
// Project root will be different for node6-transpiled code. | ||
projectRoot = fs.existsSync(path.join(__dirname, '..', 'package.json')) ? path.join(__dirname, '..') : path.join(__dirname, '..', '..'); | ||
} | ||
return projectRoot; | ||
} | ||
/** | ||
* @param {!Protocol.Runtime.ExceptionDetails} exceptionDetails | ||
@@ -64,0 +51,0 @@ * @return {string} |
@@ -41,3 +41,3 @@ /** | ||
* @param {string} key | ||
* @param {{text: string}=} options | ||
* @param {{text?: string}=} options | ||
*/ | ||
@@ -44,0 +44,0 @@ async down(key, options = { text: undefined }) { |
@@ -25,4 +25,3 @@ /** | ||
const fs = require('fs'); | ||
const {helper, assert, debugError} = require('./helper'); | ||
const ChromiumRevision = require(path.join(helper.projectRoot(), 'package.json')).puppeteer.chromium_revision; | ||
const {helper, debugError} = require('./helper'); | ||
const {TimeoutError} = require('./Errors'); | ||
@@ -60,6 +59,17 @@ | ||
/** | ||
* @param {string} projectRoot | ||
* @param {string} preferredRevision | ||
* @param {boolean} isPuppeteerCore | ||
*/ | ||
constructor(projectRoot, preferredRevision, isPuppeteerCore) { | ||
this._projectRoot = projectRoot; | ||
this._preferredRevision = preferredRevision; | ||
this._isPuppeteerCore = isPuppeteerCore; | ||
} | ||
/** | ||
* @param {!(LaunchOptions & ChromeArgOptions & BrowserOptions)=} options | ||
* @return {!Promise<!Browser>} | ||
*/ | ||
static async launch(options = {}) { | ||
async launch(options = {}) { | ||
const { | ||
@@ -100,6 +110,6 @@ ignoreDefaultArgs = false, | ||
if (!executablePath) { | ||
const browserFetcher = new BrowserFetcher(); | ||
const revisionInfo = browserFetcher.revisionInfo(ChromiumRevision); | ||
assert(revisionInfo.local, `Chromium revision is not downloaded. Run "npm install" or "yarn install"`); | ||
chromeExecutable = revisionInfo.executablePath; | ||
const {missingText, executablePath} = this._resolveExecutablePath(); | ||
if (missingText) | ||
throw new Error(missingText); | ||
chromeExecutable = executablePath; | ||
} | ||
@@ -153,3 +163,3 @@ | ||
if (!usePipe) { | ||
const browserWSEndpoint = await waitForWSEndpoint(chromeProcess, timeout); | ||
const browserWSEndpoint = await waitForWSEndpoint(chromeProcess, timeout, this._preferredRevision); | ||
connection = await Connection.createForWebSocket(browserWSEndpoint, slowMo); | ||
@@ -228,3 +238,3 @@ } else { | ||
*/ | ||
static defaultArgs(options = {}) { | ||
defaultArgs(options = {}) { | ||
const { | ||
@@ -259,13 +269,11 @@ devtools = false, | ||
*/ | ||
static executablePath() { | ||
const browserFetcher = new BrowserFetcher(); | ||
const revisionInfo = browserFetcher.revisionInfo(ChromiumRevision); | ||
return revisionInfo.executablePath; | ||
executablePath() { | ||
return this._resolveExecutablePath().executablePath; | ||
} | ||
/** | ||
* @param {!(BrowserOptions & {browserWSEndpoint: string})=} options | ||
* @param {!(BrowserOptions & {browserWSEndpoint: string})} options | ||
* @return {!Promise<!Browser>} | ||
*/ | ||
static async connect(options) { | ||
async connect(options) { | ||
const { | ||
@@ -281,2 +289,27 @@ browserWSEndpoint, | ||
} | ||
/** | ||
* @return {{executablePath: string, missingText: ?string}} | ||
*/ | ||
_resolveExecutablePath() { | ||
const browserFetcher = new BrowserFetcher(this._projectRoot); | ||
// puppeteer-core doesn't take into account PUPPETEER_* env variables. | ||
if (!this._isPuppeteerCore) { | ||
const executablePath = process.env['PUPPETEER_EXECUTABLE_PATH']; | ||
if (executablePath) { | ||
const missingText = !fs.existsSync(executablePath) ? 'Tried to use PUPPETEER_EXECUTABLE_PATH env variable to launch browser but did not find any executable at: ' + executablePath : null; | ||
return { executablePath, missingText }; | ||
} | ||
const revision = process.env['PUPPETEER_CHROMIUM_REVISION']; | ||
if (revision) { | ||
const revisionInfo = browserFetcher.revisionInfo(revision); | ||
const missingText = !revisionInfo.local ? 'Tried to use PUPPETEER_CHROMIUM_REVISION env variable to launch browser but did not find executable at: ' + revisionInfo.executablePath : null; | ||
return {executablePath: revisionInfo.executablePath, missingText}; | ||
} | ||
} | ||
const revisionInfo = browserFetcher.revisionInfo(this._preferredRevision); | ||
const missingText = !revisionInfo.local ? `Chromium revision is not downloaded. Run "npm install" or "yarn install"` : null; | ||
return {executablePath: revisionInfo.executablePath, missingText}; | ||
} | ||
} | ||
@@ -287,5 +320,6 @@ | ||
* @param {number} timeout | ||
* @param {string} preferredRevision | ||
* @return {!Promise<string>} | ||
*/ | ||
function waitForWSEndpoint(chromeProcess, timeout) { | ||
function waitForWSEndpoint(chromeProcess, timeout, preferredRevision) { | ||
return new Promise((resolve, reject) => { | ||
@@ -318,3 +352,3 @@ const rl = readline.createInterface({ input: chromeProcess.stderr }); | ||
cleanup(); | ||
reject(new TimeoutError(`Timed out after ${timeout} ms while trying to connect to Chrome! The only Chrome revision guaranteed to work is r${ChromiumRevision}`)); | ||
reject(new TimeoutError(`Timed out after ${timeout} ms while trying to connect to Chrome! The only Chrome revision guaranteed to work is r${preferredRevision}`)); | ||
} | ||
@@ -321,0 +355,0 @@ |
@@ -54,12 +54,11 @@ /** | ||
const lifecycleCompletePromise = new Promise(fulfill => { | ||
this._lifecycleCompleteCallback = fulfill; | ||
this._sameDocumentNavigationPromise = new Promise(fulfill => { | ||
this._sameDocumentNavigationCompleteCallback = fulfill; | ||
}); | ||
this._navigationPromise = Promise.race([ | ||
this._createTimeoutPromise(), | ||
lifecycleCompletePromise | ||
]).then(error => { | ||
this._cleanup(); | ||
return error; | ||
this._newDocumentNavigationPromise = new Promise(fulfill => { | ||
this._newDocumentNavigationCompleteCallback = fulfill; | ||
}); | ||
this._timeoutPromise = this._createTimeoutPromise(); | ||
} | ||
@@ -70,2 +69,23 @@ | ||
*/ | ||
sameDocumentNavigationPromise() { | ||
return this._sameDocumentNavigationPromise; | ||
} | ||
/** | ||
* @return {!Promise<?Error>} | ||
*/ | ||
newDocumentNavigationPromise() { | ||
return this._newDocumentNavigationPromise; | ||
} | ||
/** | ||
* @return {!Promise<?Error>} | ||
*/ | ||
timeoutPromise() { | ||
return this._timeoutPromise; | ||
} | ||
/** | ||
* @return {!Promise<?Error>} | ||
*/ | ||
_createTimeoutPromise() { | ||
@@ -80,9 +100,2 @@ if (!this._timeout) | ||
/** | ||
* @return {!Promise<?Error>} | ||
*/ | ||
async navigationPromise() { | ||
return this._navigationPromise; | ||
} | ||
/** | ||
* @param {!Puppeteer.Frame} frame | ||
@@ -103,3 +116,6 @@ */ | ||
return; | ||
this._lifecycleCompleteCallback(); | ||
if (this._hasSameDocumentNavigation) | ||
this._sameDocumentNavigationCompleteCallback(); | ||
if (this._frame._loaderId !== this._initialLoaderId) | ||
this._newDocumentNavigationCompleteCallback(); | ||
@@ -124,9 +140,4 @@ /** | ||
cancel() { | ||
this._cleanup(); | ||
} | ||
_cleanup() { | ||
dispose() { | ||
helper.removeEventListeners(this._eventListeners); | ||
this._lifecycleCompleteCallback(new Error('Navigation failed')); | ||
clearTimeout(this._maximumTimer); | ||
@@ -133,0 +144,0 @@ } |
@@ -195,10 +195,13 @@ /** | ||
if (request) { | ||
this._handleRequestRedirect(request, event.redirectResponse.status, event.redirectResponse.headers, event.redirectResponse.fromDiskCache, event.redirectResponse.fromServiceWorker, event.redirectResponse.securityDetails); | ||
this._handleRequestRedirect(request, event.redirectResponse); | ||
redirectChain = request._redirectChain; | ||
} | ||
} | ||
const isNavigationRequest = event.requestId === event.loaderId && event.type === 'Document'; | ||
this._handleRequestStart(event.requestId, interceptionId, event.request.url, isNavigationRequest, event.type, event.request, event.frameId, redirectChain); | ||
const frame = event.frameId ? this._frameManager.frame(event.frameId) : null; | ||
const request = new Request(this._client, frame, interceptionId, this._userRequestInterceptionEnabled, event, redirectChain); | ||
this._requestIdToRequest.set(event.requestId, request); | ||
this.emit(NetworkManager.Events.Request, request); | ||
} | ||
/** | ||
@@ -215,10 +218,6 @@ * @param {!Protocol.Network.requestServedFromCachePayload} event | ||
* @param {!Request} request | ||
* @param {number} redirectStatus | ||
* @param {!Object} redirectHeaders | ||
* @param {boolean} fromDiskCache | ||
* @param {boolean} fromServiceWorker | ||
* @param {?Object} securityDetails | ||
* @param {!Protocol.Network.Response} responsePayload | ||
*/ | ||
_handleRequestRedirect(request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails) { | ||
const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails); | ||
_handleRequestRedirect(request, responsePayload) { | ||
const response = new Response(this._client, request, responsePayload); | ||
request._response = response; | ||
@@ -234,21 +233,2 @@ request._redirectChain.push(request); | ||
/** | ||
* @param {string} requestId | ||
* @param {?string} interceptionId | ||
* @param {string} url | ||
* @param {boolean} isNavigationRequest | ||
* @param {string} resourceType | ||
* @param {!Protocol.Network.Request} requestPayload | ||
* @param {?string} frameId | ||
* @param {!Array<!Request>} redirectChain | ||
*/ | ||
_handleRequestStart(requestId, interceptionId, url, isNavigationRequest, resourceType, requestPayload, frameId, redirectChain) { | ||
let frame = null; | ||
if (frameId) | ||
frame = this._frameManager.frame(frameId); | ||
const request = new Request(this._client, requestId, interceptionId, isNavigationRequest, this._userRequestInterceptionEnabled, url, resourceType, requestPayload, frame, redirectChain); | ||
this._requestIdToRequest.set(requestId, request); | ||
this.emit(NetworkManager.Events.Request, request); | ||
} | ||
/** | ||
* @param {!Protocol.Network.responseReceivedPayload} event | ||
@@ -261,4 +241,3 @@ */ | ||
return; | ||
const response = new Response(this._client, request, event.response.status, event.response.headers, | ||
event.response.fromDiskCache, event.response.fromServiceWorker, event.response.securityDetails); | ||
const response = new Response(this._client, request, event.response); | ||
request._response = response; | ||
@@ -305,16 +284,12 @@ this.emit(NetworkManager.Events.Response, response); | ||
* @param {!Puppeteer.CDPSession} client | ||
* @param {?string} requestId | ||
* @param {?Puppeteer.Frame} frame | ||
* @param {string} interceptionId | ||
* @param {boolean} isNavigationRequest | ||
* @param {boolean} allowInterception | ||
* @param {string} url | ||
* @param {string} resourceType | ||
* @param {!Protocol.Network.Request} payload | ||
* @param {?Puppeteer.Frame} frame | ||
* @param {!Protocol.Network.requestWillBeSentPayload} event | ||
* @param {!Array<!Request>} redirectChain | ||
*/ | ||
constructor(client, requestId, interceptionId, isNavigationRequest, allowInterception, url, resourceType, payload, frame, redirectChain) { | ||
constructor(client, frame, interceptionId, allowInterception, event, redirectChain) { | ||
this._client = client; | ||
this._requestId = requestId; | ||
this._isNavigationRequest = isNavigationRequest; | ||
this._requestId = event.requestId; | ||
this._isNavigationRequest = event.requestId === event.loaderId && event.type === 'Document'; | ||
this._interceptionId = interceptionId; | ||
@@ -326,11 +301,11 @@ this._allowInterception = allowInterception; | ||
this._url = url; | ||
this._resourceType = resourceType.toLowerCase(); | ||
this._method = payload.method; | ||
this._postData = payload.postData; | ||
this._url = event.request.url; | ||
this._resourceType = event.type.toLowerCase(); | ||
this._method = event.request.method; | ||
this._postData = event.request.postData; | ||
this._headers = {}; | ||
this._frame = frame; | ||
this._redirectChain = redirectChain; | ||
for (const key of Object.keys(payload.headers)) | ||
this._headers[key.toLowerCase()] = payload.headers[key]; | ||
for (const key of Object.keys(event.request.headers)) | ||
this._headers[key.toLowerCase()] = event.request.headers[key]; | ||
@@ -362,3 +337,3 @@ this._fromMemoryCache = false; | ||
/** | ||
* @return {string} | ||
* @return {string|undefined} | ||
*/ | ||
@@ -526,9 +501,5 @@ postData() { | ||
* @param {!Request} request | ||
* @param {number} status | ||
* @param {!Object} headers | ||
* @param {boolean} fromDiskCache | ||
* @param {boolean} fromServiceWorker | ||
* @param {?Object} securityDetails | ||
* @param {!Protocol.Network.Response} responsePayload | ||
*/ | ||
constructor(client, request, status, headers, fromDiskCache, fromServiceWorker, securityDetails) { | ||
constructor(client, request, responsePayload) { | ||
this._client = client; | ||
@@ -542,21 +513,25 @@ this._request = request; | ||
this._status = status; | ||
this._remoteAddress = { | ||
ip: responsePayload.remoteIPAddress, | ||
port: responsePayload.remotePort, | ||
}; | ||
this._status = responsePayload.status; | ||
this._statusText = responsePayload.statusText; | ||
this._url = request.url(); | ||
this._fromDiskCache = fromDiskCache; | ||
this._fromServiceWorker = fromServiceWorker; | ||
this._fromDiskCache = !!responsePayload.fromDiskCache; | ||
this._fromServiceWorker = !!responsePayload.fromServiceWorker; | ||
this._headers = {}; | ||
for (const key of Object.keys(headers)) | ||
this._headers[key.toLowerCase()] = headers[key]; | ||
this._securityDetails = null; | ||
if (securityDetails) { | ||
this._securityDetails = new SecurityDetails( | ||
securityDetails['subjectName'], | ||
securityDetails['issuer'], | ||
securityDetails['validFrom'], | ||
securityDetails['validTo'], | ||
securityDetails['protocol']); | ||
} | ||
for (const key of Object.keys(responsePayload.headers)) | ||
this._headers[key.toLowerCase()] = responsePayload.headers[key]; | ||
this._securityDetails = responsePayload.securityDetails ? new SecurityDetails(responsePayload.securityDetails) : null; | ||
} | ||
/** | ||
* @return {{ip: string, port: number}} | ||
*/ | ||
remoteAddress() { | ||
return this._remoteAddress; | ||
} | ||
/** | ||
* @return {string} | ||
@@ -583,2 +558,9 @@ */ | ||
/** | ||
* @return {string} | ||
*/ | ||
statusText() { | ||
return this._statusText; | ||
} | ||
/** | ||
* @return {!Object} | ||
@@ -689,15 +671,10 @@ */ | ||
/** | ||
* @param {string} subjectName | ||
* @param {string} issuer | ||
* @param {number} validFrom | ||
* @param {number} validTo | ||
* @param {string} protocol | ||
* @param {!Protocol.Network.SecurityDetails} securityPayload | ||
*/ | ||
constructor(subjectName, issuer, validFrom, validTo, protocol) { | ||
this._subjectName = subjectName; | ||
this._issuer = issuer; | ||
this._validFrom = validFrom; | ||
this._validTo = validTo; | ||
this._protocol = protocol; | ||
constructor(securityPayload) { | ||
this._subjectName = securityPayload['subjectName']; | ||
this._issuer = securityPayload['issuer']; | ||
this._validFrom = securityPayload['validFrom']; | ||
this._validTo = securityPayload['validTo']; | ||
this._protocol = securityPayload['protocol']; | ||
} | ||
@@ -704,0 +681,0 @@ |
@@ -30,2 +30,3 @@ /** | ||
const {Worker} = require('./Worker'); | ||
const {createJSHandle} = require('./ExecutionContext'); | ||
@@ -148,2 +149,16 @@ const writeFileAsync = helper.promisify(fs.writeFile); | ||
/** | ||
* @param {!{longitude: number, latitude: number, accuracy: (number|undefined)}} options | ||
*/ | ||
async setGeolocation(options) { | ||
const { longitude, latitude, accuracy = 0} = options; | ||
if (longitude < -180 || longitude > 180) | ||
throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`); | ||
if (latitude < -90 || latitude > 90) | ||
throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`); | ||
if (accuracy < 0) | ||
throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`); | ||
await this._client.send('Emulation.setGeolocationOverride', {longitude, latitude, accuracy}); | ||
} | ||
/** | ||
* @return {!Puppeteer.Target} | ||
@@ -485,3 +500,3 @@ */ | ||
const context = this._frameManager.executionContextById(event.executionContextId); | ||
const values = event.args.map(arg => this._frameManager.createJSHandle(context, arg)); | ||
const values = event.args.map(arg => createJSHandle(context, arg)); | ||
this._addConsoleMessage(event.type, values); | ||
@@ -568,3 +583,3 @@ } | ||
async goto(url, options = {}) { | ||
const referrer = this._networkManager.extraHTTPHeaders()['referer']; | ||
const referrer = typeof options.referer === 'string' ? options.referer : this._networkManager.extraHTTPHeaders()['referer']; | ||
@@ -583,10 +598,14 @@ /** @type {Map<string, !Puppeteer.Request>} */ | ||
const watcher = new NavigatorWatcher(this._frameManager, mainFrame, timeout, options); | ||
const navigationPromise = watcher.navigationPromise(); | ||
let ensureNewDocumentNavigation = false; | ||
let error = await Promise.race([ | ||
navigate(this._client, url, referrer), | ||
navigationPromise, | ||
watcher.timeoutPromise(), | ||
]); | ||
if (!error) | ||
error = await navigationPromise; | ||
watcher.cancel(); | ||
if (!error) { | ||
error = await Promise.race([ | ||
watcher.timeoutPromise(), | ||
ensureNewDocumentNavigation ? watcher.newDocumentNavigationPromise() : watcher.sameDocumentNavigationPromise(), | ||
]); | ||
} | ||
watcher.dispose(); | ||
helper.removeEventListeners(eventListeners); | ||
@@ -607,2 +626,3 @@ if (error) | ||
const response = await client.send('Page.navigate', {url, referrer}); | ||
ensureNewDocumentNavigation = !!response.loaderId; | ||
return response.errorText ? new Error(`${response.errorText} at ${url}`) : null; | ||
@@ -638,3 +658,8 @@ } catch (error) { | ||
const listener = helper.addEventListener(this._networkManager, NetworkManager.Events.Response, response => responses.set(response.url(), response)); | ||
const error = await watcher.navigationPromise(); | ||
const error = await Promise.race([ | ||
watcher.timeoutPromise(), | ||
watcher.sameDocumentNavigationPromise(), | ||
watcher.newDocumentNavigationPromise() | ||
]); | ||
watcher.dispose(); | ||
helper.removeEventListeners([listener]); | ||
@@ -843,2 +868,3 @@ if (error) | ||
if (options.fullPage) { | ||
assert(this._viewport, 'fullPage screenshots do not work without first setting viewport.'); | ||
const metrics = await this._client.send('Page.getLayoutMetrics'); | ||
@@ -845,0 +871,0 @@ const width = Math.ceil(metrics.contentSize.width); |
@@ -22,7 +22,17 @@ /** | ||
/** | ||
* @param {string} projectRoot | ||
* @param {string} preferredRevision | ||
* @param {boolean} isPuppeteerCore | ||
*/ | ||
constructor(projectRoot, preferredRevision, isPuppeteerCore) { | ||
this._projectRoot = projectRoot; | ||
this._launcher = new Launcher(projectRoot, preferredRevision, isPuppeteerCore); | ||
} | ||
/** | ||
* @param {!Object=} options | ||
* @return {!Promise<!Puppeteer.Browser>} | ||
*/ | ||
static launch(options) { | ||
return Launcher.launch(options); | ||
launch(options) { | ||
return this._launcher.launch(options); | ||
} | ||
@@ -34,4 +44,4 @@ | ||
*/ | ||
static connect(options) { | ||
return Launcher.connect(options); | ||
connect(options) { | ||
return this._launcher.connect(options); | ||
} | ||
@@ -42,4 +52,4 @@ | ||
*/ | ||
static executablePath() { | ||
return Launcher.executablePath(); | ||
executablePath() { | ||
return this._launcher.executablePath(); | ||
} | ||
@@ -50,4 +60,4 @@ | ||
*/ | ||
static defaultArgs(options) { | ||
return Launcher.defaultArgs(options); | ||
defaultArgs(options) { | ||
return this._launcher.defaultArgs(options); | ||
} | ||
@@ -59,4 +69,4 @@ | ||
*/ | ||
static createBrowserFetcher(options) { | ||
return new BrowserFetcher(options); | ||
createBrowserFetcher(options) { | ||
return new BrowserFetcher(this._projectRoot, options); | ||
} | ||
@@ -63,0 +73,0 @@ }; |
@@ -80,3 +80,3 @@ const {Page} = require('./Page'); | ||
/** | ||
* @return {Puppeteer.Target} | ||
* @return {?Puppeteer.Target} | ||
*/ | ||
@@ -83,0 +83,0 @@ opener() { |
@@ -36,3 +36,3 @@ /** | ||
jsHandleFactory = remoteObject => new JSHandle(executionContext, client, remoteObject); | ||
const executionContext = new ExecutionContext(client, event.context, jsHandleFactory, null); | ||
const executionContext = new ExecutionContext(client, event.context, null); | ||
this._executionContextCallback(executionContext); | ||
@@ -39,0 +39,0 @@ }); |
@@ -40,7 +40,7 @@ /** | ||
this._defaultContext = new BrowserContext(this, null); | ||
this._defaultContext = new BrowserContext(this._connection, this, null); | ||
/** @type {Map<string, BrowserContext>} */ | ||
this._contexts = new Map(); | ||
for (const contextId of contextIds) | ||
this._contexts.set(contextId, new BrowserContext(this, contextId)); | ||
this._contexts.set(contextId, new BrowserContext(this._connection, this, contextId)); | ||
@@ -95,3 +95,3 @@ /** @type {Map<string, Target>} */ | ||
const {browserContextId} = (yield this._connection.send('Target.createBrowserContext')); | ||
const context = new BrowserContext(this, browserContextId); | ||
const context = new BrowserContext(this._connection, this, browserContextId); | ||
this._contexts.set(browserContextId, context); | ||
@@ -109,2 +109,9 @@ return context; | ||
/** | ||
* @return {!BrowserContext} | ||
*/ | ||
defaultBrowserContext() { | ||
return this._defaultContext; | ||
} | ||
/** | ||
* @param {?string} contextId | ||
@@ -323,3 +330,3 @@ */ | ||
/** | ||
* @param {string} contextId | ||
* @param {?string} contextId | ||
* @return {!Promise<!Puppeteer.Page>} | ||
@@ -524,7 +531,9 @@ */ | ||
/** | ||
* @param {!Puppeteer.Connection} connection | ||
* @param {!Browser} browser | ||
* @param {?string} contextId | ||
*/ | ||
constructor(browser, contextId) { | ||
constructor(connection, browser, contextId) { | ||
super(); | ||
this._connection = connection; | ||
this._browser = browser; | ||
@@ -587,2 +596,91 @@ this._id = contextId; | ||
/** | ||
* @param {string} origin | ||
* @param {!Array<string>} permissions | ||
*/ | ||
/* async */ overridePermissions(origin, permissions) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const webPermissionToProtocol = new Map([ | ||
['geolocation', 'geolocation'], | ||
['midi', 'midi'], | ||
['notifications', 'notifications'], | ||
['push', 'push'], | ||
['camera', 'videoCapture'], | ||
['microphone', 'audioCapture'], | ||
['background-sync', 'backgroundSync'], | ||
['ambient-light-sensor', 'sensors'], | ||
['accelerometer', 'sensors'], | ||
['gyroscope', 'sensors'], | ||
['magnetometer', 'sensors'], | ||
['accessibility-events', 'accessibilityEvents'], | ||
['clipboard-read', 'clipboardRead'], | ||
['clipboard-write', 'clipboardWrite'], | ||
['payment-handler', 'paymentHandler'], | ||
// chrome-specific permissions we have. | ||
['midi-sysex', 'midiSysex'], | ||
]); | ||
permissions = permissions.map(permission => { | ||
const protocolPermission = webPermissionToProtocol.get(permission); | ||
if (!protocolPermission) | ||
throw new Error('Unknown permission: ' + permission); | ||
return protocolPermission; | ||
}); | ||
(yield this._connection.send('Browser.grantPermissions', {origin, browserContextId: this._id || undefined, permissions})); | ||
});} | ||
/* async */ clearPermissionOverrides() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
(yield this._connection.send('Browser.resetPermissions', {browserContextId: this._id || undefined})); | ||
});} | ||
/** | ||
* @return {!Promise<!Puppeteer.Page>} | ||
@@ -589,0 +687,0 @@ */ |
@@ -52,6 +52,7 @@ /** | ||
/** | ||
* @param {string} projectRoot | ||
* @param {!BrowserFetcher.Options=} options | ||
*/ | ||
constructor(options = {}) { | ||
this._downloadsFolder = options.path || path.join(helper.projectRoot(), '.local-chromium'); | ||
constructor(projectRoot, options = {}) { | ||
this._downloadsFolder = options.path || path.join(projectRoot, '.local-chromium'); | ||
this._downloadHost = options.host || DEFAULT_DOWNLOAD_HOST; | ||
@@ -338,4 +339,3 @@ this._platform = options.platform || ''; | ||
const driver = options.protocol === 'https:' ? 'https' : 'http'; | ||
const request = require(driver).request(options, res => { | ||
const requestCallback = res => { | ||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) | ||
@@ -345,3 +345,6 @@ httpRequest(res.headers.location, method, response); | ||
response(res); | ||
}); | ||
}; | ||
const request = options.protocol === 'https:' ? | ||
require('https').request(options, requestCallback) : | ||
require('http').request(options, requestCallback); | ||
request.end(); | ||
@@ -348,0 +351,0 @@ return request; |
@@ -253,2 +253,3 @@ /** | ||
this._callbacks = new Map(); | ||
/** @type {null|Connection|CDPSession} */ | ||
this._connection = connection; | ||
@@ -342,2 +343,4 @@ this._targetType = targetType; | ||
})(function*(){ | ||
if (!this._connection) | ||
throw new Error(`Session already detached. Most likely the ${this._targetType} has been closed.`); | ||
(yield this._connection.send('Target.detachFromTarget', {sessionId: this._sessionId})); | ||
@@ -375,4 +378,3 @@ });} | ||
message += ` ${object.error.data}`; | ||
if (object.error.message) | ||
return rewriteError(error, message); | ||
return rewriteError(error, message); | ||
} | ||
@@ -379,0 +381,0 @@ |
@@ -17,3 +17,4 @@ /** | ||
const {helper, assert} = require('./helper'); | ||
const {helper, assert, debugError} = require('./helper'); | ||
const path = require('path'); | ||
@@ -23,2 +24,11 @@ const EVALUATION_SCRIPT_URL = '__puppeteer_evaluation_script__'; | ||
function createJSHandle(context, remoteObject) { | ||
const frame = context.frame(); | ||
if (remoteObject.subtype === 'node' && frame) { | ||
const frameManager = frame._frameManager; | ||
return new ElementHandle(context, context._client, remoteObject, frameManager.page(), frameManager); | ||
} | ||
return new JSHandle(context, context._client, remoteObject); | ||
} | ||
class ExecutionContext { | ||
@@ -28,6 +38,5 @@ /** | ||
* @param {!Protocol.Runtime.ExecutionContextDescription} contextPayload | ||
* @param {function(!Protocol.Runtime.RemoteObject):!JSHandle} objectHandleFactory | ||
* @param {?Puppeteer.Frame} frame | ||
*/ | ||
constructor(client, contextPayload, objectHandleFactory, frame) { | ||
constructor(client, contextPayload, frame) { | ||
this._client = client; | ||
@@ -37,3 +46,2 @@ this._frame = frame; | ||
this._isDefault = contextPayload.auxData ? !!contextPayload.auxData['isDefault'] : false; | ||
this._objectHandleFactory = objectHandleFactory; | ||
} | ||
@@ -139,3 +147,3 @@ | ||
throw new Error('Evaluation failed: ' + helper.getExceptionMessage(exceptionDetails)); | ||
return this._objectHandleFactory(remoteObject); | ||
return createJSHandle(this, remoteObject); | ||
} | ||
@@ -156,3 +164,3 @@ | ||
throw new Error('Evaluation failed: ' + helper.getExceptionMessage(exceptionDetails)); | ||
return this._objectHandleFactory(remoteObject); | ||
return createJSHandle(this, remoteObject); | ||
@@ -235,3 +243,3 @@ /** | ||
})); | ||
return this._objectHandleFactory(response.objects); | ||
return createJSHandle(this, response.objects); | ||
});} | ||
@@ -340,3 +348,3 @@ } | ||
continue; | ||
result.set(property.name, this._context._objectHandleFactory(property.value)); | ||
result.set(property.name, createJSHandle(this._context, property.value)); | ||
} | ||
@@ -441,3 +449,899 @@ return result; | ||
class ElementHandle extends JSHandle { | ||
/** | ||
* @param {!Puppeteer.ExecutionContext} context | ||
* @param {!Puppeteer.CDPSession} client | ||
* @param {!Protocol.Runtime.RemoteObject} remoteObject | ||
* @param {!Puppeteer.Page} page | ||
* @param {!Puppeteer.FrameManager} frameManager | ||
*/ | ||
constructor(context, client, remoteObject, page, frameManager) { | ||
super(context, client, remoteObject); | ||
this._client = client; | ||
this._remoteObject = remoteObject; | ||
this._page = page; | ||
this._frameManager = frameManager; | ||
this._disposed = false; | ||
} | ||
/** | ||
* @override | ||
* @return {?ElementHandle} | ||
*/ | ||
asElement() { | ||
return this; | ||
} | ||
/** | ||
* @return {!Promise<?Puppeteer.Frame>} | ||
*/ | ||
/* async */ contentFrame() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const nodeInfo = (yield this._client.send('DOM.describeNode', { | ||
objectId: this._remoteObject.objectId | ||
})); | ||
if (typeof nodeInfo.node.frameId !== 'string') | ||
return null; | ||
return this._frameManager.frame(nodeInfo.node.frameId); | ||
});} | ||
/* async */ _scrollIntoViewIfNeeded() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const error = (yield this.executionContext().evaluate(/* async */(element, pageJavascriptEnabled) => {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
if (!element.isConnected) | ||
return 'Node is detached from document'; | ||
if (element.nodeType !== Node.ELEMENT_NODE) | ||
return 'Node is not of type HTMLElement'; | ||
// force-scroll if page's javascript is disabled. | ||
if (!pageJavascriptEnabled) { | ||
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'}); | ||
return false; | ||
} | ||
const visibleRatio = (yield new Promise(resolve => { | ||
const observer = new IntersectionObserver(entries => { | ||
resolve(entries[0].intersectionRatio); | ||
observer.disconnect(); | ||
}); | ||
observer.observe(element); | ||
})); | ||
if (visibleRatio !== 1.0) | ||
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'}); | ||
return false; | ||
});}, this, this._page._javascriptEnabled)); | ||
if (error) | ||
throw new Error(error); | ||
});} | ||
/** | ||
* @return {!Promise<!{x: number, y: number}>} | ||
*/ | ||
/* async */ _clickablePoint() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const result = (yield this._client.send('DOM.getContentQuads', { | ||
objectId: this._remoteObject.objectId | ||
}).catch(debugError)); | ||
if (!result || !result.quads.length) | ||
throw new Error('Node is either not visible or not an HTMLElement'); | ||
// Filter out quads that have too small area to click into. | ||
const quads = result.quads.map(quad => this._fromProtocolQuad(quad)).filter(quad => computeQuadArea(quad) > 1); | ||
if (!quads.length) | ||
throw new Error('Node is either not visible or not an HTMLElement'); | ||
// Return the middle point of the first quad. | ||
const quad = quads[0]; | ||
let x = 0; | ||
let y = 0; | ||
for (const point of quad) { | ||
x += point.x; | ||
y += point.y; | ||
} | ||
return { | ||
x: x / 4, | ||
y: y / 4 | ||
}; | ||
});} | ||
/** | ||
* @return {!Promise<void|Protocol.DOM.getBoxModelReturnValue>} | ||
*/ | ||
_getBoxModel() { | ||
return this._client.send('DOM.getBoxModel', { | ||
objectId: this._remoteObject.objectId | ||
}).catch(error => debugError(error)); | ||
} | ||
/** | ||
* @param {!Array<number>} quad | ||
* @return {!Array<object>} | ||
*/ | ||
_fromProtocolQuad(quad) { | ||
return [ | ||
{x: quad[0], y: quad[1]}, | ||
{x: quad[2], y: quad[3]}, | ||
{x: quad[4], y: quad[5]}, | ||
{x: quad[6], y: quad[7]} | ||
]; | ||
} | ||
/* async */ hover() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
(yield this._scrollIntoViewIfNeeded()); | ||
const {x, y} = (yield this._clickablePoint()); | ||
(yield this._page.mouse.move(x, y)); | ||
});} | ||
/** | ||
* @param {!Object=} options | ||
*/ | ||
/* async */ click(options = {}) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
(yield this._scrollIntoViewIfNeeded()); | ||
const {x, y} = (yield this._clickablePoint()); | ||
(yield this._page.mouse.click(x, y, options)); | ||
});} | ||
/** | ||
* @param {!Array<string>} filePaths | ||
* @return {!Promise} | ||
*/ | ||
/* async */ uploadFile(...filePaths) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const files = filePaths.map(filePath => path.resolve(filePath)); | ||
const objectId = this._remoteObject.objectId; | ||
return this._client.send('DOM.setFileInputFiles', { objectId, files }); | ||
});} | ||
/* async */ tap() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
(yield this._scrollIntoViewIfNeeded()); | ||
const {x, y} = (yield this._clickablePoint()); | ||
(yield this._page.touchscreen.tap(x, y)); | ||
});} | ||
/* async */ focus() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
(yield this.executionContext().evaluate(element => element.focus(), this)); | ||
});} | ||
/** | ||
* @param {string} text | ||
* @param {{delay: (number|undefined)}=} options | ||
*/ | ||
/* async */ type(text, options) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
(yield this.focus()); | ||
(yield this._page.keyboard.type(text, options)); | ||
});} | ||
/** | ||
* @param {string} key | ||
* @param {!Object=} options | ||
*/ | ||
/* async */ press(key, options) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
(yield this.focus()); | ||
(yield this._page.keyboard.press(key, options)); | ||
});} | ||
/** | ||
* @return {!Promise<?{x: number, y: number, width: number, height: number}>} | ||
*/ | ||
/* async */ boundingBox() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const result = (yield this._getBoxModel()); | ||
if (!result) | ||
return null; | ||
const quad = result.model.border; | ||
const x = Math.min(quad[0], quad[2], quad[4], quad[6]); | ||
const y = Math.min(quad[1], quad[3], quad[5], quad[7]); | ||
const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x; | ||
const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y; | ||
return {x, y, width, height}; | ||
});} | ||
/** | ||
* @return {!Promise<?object>} | ||
*/ | ||
/* async */ boxModel() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const result = (yield this._getBoxModel()); | ||
if (!result) | ||
return null; | ||
const {content, padding, border, margin, width, height} = result.model; | ||
return { | ||
content: this._fromProtocolQuad(content), | ||
padding: this._fromProtocolQuad(padding), | ||
border: this._fromProtocolQuad(border), | ||
margin: this._fromProtocolQuad(margin), | ||
width, | ||
height | ||
}; | ||
});} | ||
/** | ||
* | ||
* @param {!Object=} options | ||
* @returns {!Promise<Object>} | ||
*/ | ||
/* async */ screenshot(options = {}) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
let needsViewportReset = false; | ||
let boundingBox = (yield this.boundingBox()); | ||
assert(boundingBox, 'Node is either not visible or not an HTMLElement'); | ||
const viewport = this._page.viewport(); | ||
if (viewport && (boundingBox.width > viewport.width || boundingBox.height > viewport.height)) { | ||
const newViewport = { | ||
width: Math.max(viewport.width, Math.ceil(boundingBox.width)), | ||
height: Math.max(viewport.height, Math.ceil(boundingBox.height)), | ||
}; | ||
(yield this._page.setViewport(Object.assign({}, viewport, newViewport))); | ||
needsViewportReset = true; | ||
} | ||
(yield this._scrollIntoViewIfNeeded()); | ||
boundingBox = (yield this.boundingBox()); | ||
assert(boundingBox, 'Node is either not visible or not an HTMLElement'); | ||
const { layoutViewport: { pageX, pageY } } = (yield this._client.send('Page.getLayoutMetrics')); | ||
const clip = Object.assign({}, boundingBox); | ||
clip.x += pageX; | ||
clip.y += pageY; | ||
const imageData = (yield this._page.screenshot(Object.assign({}, { | ||
clip | ||
}, options))); | ||
if (needsViewportReset) | ||
(yield this._page.setViewport(viewport)); | ||
return imageData; | ||
});} | ||
/** | ||
* @param {string} selector | ||
* @return {!Promise<?ElementHandle>} | ||
*/ | ||
/* async */ $(selector) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const handle = (yield this.executionContext().evaluateHandle( | ||
(element, selector) => element.querySelector(selector), | ||
this, selector | ||
)); | ||
const element = handle.asElement(); | ||
if (element) | ||
return element; | ||
(yield handle.dispose()); | ||
return null; | ||
});} | ||
/** | ||
* @param {string} selector | ||
* @return {!Promise<!Array<!ElementHandle>>} | ||
*/ | ||
/* async */ $$(selector) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const arrayHandle = (yield this.executionContext().evaluateHandle( | ||
(element, selector) => element.querySelectorAll(selector), | ||
this, selector | ||
)); | ||
const properties = (yield arrayHandle.getProperties()); | ||
(yield arrayHandle.dispose()); | ||
const result = []; | ||
for (const property of properties.values()) { | ||
const elementHandle = property.asElement(); | ||
if (elementHandle) | ||
result.push(elementHandle); | ||
} | ||
return result; | ||
});} | ||
/** | ||
* @param {string} selector | ||
* @param {Function|String} pageFunction | ||
* @param {!Array<*>} args | ||
* @return {!Promise<(!Object|undefined)>} | ||
*/ | ||
/* async */ $eval(selector, pageFunction, ...args) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const elementHandle = (yield this.$(selector)); | ||
if (!elementHandle) | ||
throw new Error(`Error: failed to find element matching selector "${selector}"`); | ||
const result = (yield this.executionContext().evaluate(pageFunction, elementHandle, ...args)); | ||
(yield elementHandle.dispose()); | ||
return result; | ||
});} | ||
/** | ||
* @param {string} selector | ||
* @param {Function|String} pageFunction | ||
* @param {!Array<*>} args | ||
* @return {!Promise<(!Object|undefined)>} | ||
*/ | ||
/* async */ $$eval(selector, pageFunction, ...args) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const arrayHandle = (yield this.executionContext().evaluateHandle( | ||
(element, selector) => Array.from(element.querySelectorAll(selector)), | ||
this, selector | ||
)); | ||
const result = (yield this.executionContext().evaluate(pageFunction, arrayHandle, ...args)); | ||
(yield arrayHandle.dispose()); | ||
return result; | ||
});} | ||
/** | ||
* @param {string} expression | ||
* @return {!Promise<!Array<!ElementHandle>>} | ||
*/ | ||
/* async */ $x(expression) {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const arrayHandle = (yield this.executionContext().evaluateHandle( | ||
(element, expression) => { | ||
const document = element.ownerDocument || element; | ||
const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE); | ||
const array = []; | ||
let item; | ||
while ((item = iterator.iterateNext())) | ||
array.push(item); | ||
return array; | ||
}, | ||
this, expression | ||
)); | ||
const properties = (yield arrayHandle.getProperties()); | ||
(yield arrayHandle.dispose()); | ||
const result = []; | ||
for (const property of properties.values()) { | ||
const elementHandle = property.asElement(); | ||
if (elementHandle) | ||
result.push(elementHandle); | ||
} | ||
return result; | ||
});} | ||
/** | ||
* @returns {!Promise<boolean>} | ||
*/ | ||
isIntersectingViewport() { | ||
return this.executionContext().evaluate(/* async */ element => {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
const visibleRatio = (yield new Promise(resolve => { | ||
const observer = new IntersectionObserver(entries => { | ||
resolve(entries[0].intersectionRatio); | ||
observer.disconnect(); | ||
}); | ||
observer.observe(element); | ||
})); | ||
return visibleRatio > 0; | ||
});}, this); | ||
} | ||
} | ||
function computeQuadArea(quad) { | ||
// Compute sum of all directed areas of adjacent triangles | ||
// https://en.wikipedia.org/wiki/Polygon#Simple_polygons | ||
let area = 0; | ||
for (let i = 0; i < quad.length; ++i) { | ||
const p1 = quad[i]; | ||
const p2 = quad[(i + 1) % quad.length]; | ||
area += (p1.x * p2.y - p2.x * p1.y) / 2; | ||
} | ||
return area; | ||
} | ||
helper.tracePublicAPI(ElementHandle); | ||
helper.tracePublicAPI(JSHandle); | ||
module.exports = {ExecutionContext, JSHandle, EVALUATION_SCRIPT_URL}; | ||
helper.tracePublicAPI(ExecutionContext); | ||
module.exports = {ExecutionContext, JSHandle, ElementHandle, createJSHandle, EVALUATION_SCRIPT_URL}; |
@@ -20,4 +20,3 @@ /** | ||
const {helper, assert} = require('./helper'); | ||
const {ExecutionContext, JSHandle} = require('./ExecutionContext'); | ||
const {ElementHandle} = require('./ElementHandle'); | ||
const {ExecutionContext} = require('./ExecutionContext'); | ||
const {TimeoutError} = require('./Errors'); | ||
@@ -92,2 +91,9 @@ | ||
/** | ||
* @return {!Puppeteer.Page} | ||
*/ | ||
page() { | ||
return this._page; | ||
} | ||
/** | ||
* @return {!Frame} | ||
@@ -117,3 +123,2 @@ */ | ||
* @param {?string} parentFrameId | ||
* @return {?Frame} | ||
*/ | ||
@@ -125,3 +130,3 @@ _onFrameAttached(frameId, parentFrameId) { | ||
const parentFrame = this._frames.get(parentFrameId); | ||
const frame = new Frame(this._client, parentFrame, frameId); | ||
const frame = new Frame(this, this._client, parentFrame, frameId); | ||
this._frames.set(frame._id, frame); | ||
@@ -153,3 +158,3 @@ this.emit(FrameManager.Events.FrameAttached, frame); | ||
// Initial main frame navigation. | ||
frame = new Frame(this._client, null, framePayload.id); | ||
frame = new Frame(this, this._client, null, framePayload.id); | ||
} | ||
@@ -192,3 +197,3 @@ this._frames.set(framePayload.id, frame); | ||
/** @type {!ExecutionContext} */ | ||
const context = new ExecutionContext(this._client, contextPayload, obj => this.createJSHandle(context, obj), frame); | ||
const context = new ExecutionContext(this._client, contextPayload, frame); | ||
this._contextIdToContext.set(contextPayload.id, context); | ||
@@ -230,13 +235,2 @@ if (frame) | ||
/** | ||
* @param {!ExecutionContext} context | ||
* @param {!Protocol.Runtime.RemoteObject} remoteObject | ||
* @return {!JSHandle} | ||
*/ | ||
createJSHandle(context, remoteObject) { | ||
if (remoteObject.subtype === 'node') | ||
return new ElementHandle(context, this._client, remoteObject, this._page, this); | ||
return new JSHandle(context, this._client, remoteObject); | ||
} | ||
/** | ||
* @param {!Frame} frame | ||
@@ -269,2 +263,3 @@ */ | ||
/** | ||
* @param {!FrameManager} frameManager | ||
* @param {!Puppeteer.CDPSession} client | ||
@@ -274,3 +269,4 @@ * @param {?Frame} parentFrame | ||
*/ | ||
constructor(client, parentFrame, frameId) { | ||
constructor(frameManager, client, parentFrame, frameId) { | ||
this._frameManager = frameManager; | ||
this._client = client; | ||
@@ -280,10 +276,12 @@ this._parentFrame = parentFrame; | ||
this._id = frameId; | ||
this._detached = false; | ||
/** @type {?Promise<!ElementHandle>} */ | ||
/** @type {?Promise<!Puppeteer.ElementHandle>} */ | ||
this._documentPromise = null; | ||
/** @type {?Promise<!ExecutionContext>} */ | ||
this._contextPromise = null; | ||
/** @type {!Promise<!ExecutionContext>} */ | ||
this._contextPromise; | ||
this._contextResolveCallback = null; | ||
this._setDefaultContext(null); | ||
/** @type {!Set<!WaitTask>} */ | ||
@@ -415,3 +413,3 @@ this._waitTasks = new Set(); | ||
* @param {string} selector | ||
* @return {!Promise<?ElementHandle>} | ||
* @return {!Promise<?Puppeteer.ElementHandle>} | ||
*/ | ||
@@ -451,3 +449,3 @@ /* async */ $(selector) {return (fn => { | ||
/** | ||
* @return {!Promise<!ElementHandle>} | ||
* @return {!Promise<!Puppeteer.ElementHandle>} | ||
*/ | ||
@@ -518,3 +516,3 @@ /* async */ _document() {return (fn => { | ||
* @param {string} expression | ||
* @return {!Promise<!Array<!ElementHandle>>} | ||
* @return {!Promise<!Array<!Puppeteer.ElementHandle>>} | ||
*/ | ||
@@ -630,3 +628,3 @@ /* async */ $x(expression) {return (fn => { | ||
* @param {string} selector | ||
* @return {!Promise<!Array<!ElementHandle>>} | ||
* @return {!Promise<!Array<!Puppeteer.ElementHandle>>} | ||
*/ | ||
@@ -779,3 +777,3 @@ /* async */ $$(selector) {return (fn => { | ||
* @param {Object} options | ||
* @return {!Promise<!ElementHandle>} | ||
* @return {!Promise<!Puppeteer.ElementHandle>} | ||
*/ | ||
@@ -898,3 +896,3 @@ /* async */ addScriptTag(options) {return (fn => { | ||
* @param {Object} options | ||
* @return {!Promise<!ElementHandle>} | ||
* @return {!Promise<!Puppeteer.ElementHandle>} | ||
*/ | ||
@@ -1495,3 +1493,3 @@ /* async */ addStyleTag(options) {return (fn => { | ||
const runCount = ++this._runCount; | ||
/** @type {?JSHandle} */ | ||
/** @type {?Puppeteer.JSHandle} */ | ||
let success = null; | ||
@@ -1498,0 +1496,0 @@ let error = null; |
@@ -16,4 +16,2 @@ /** | ||
*/ | ||
const fs = require('fs'); | ||
const path = require('path'); | ||
const {TimeoutError} = require('./Errors'); | ||
@@ -24,3 +22,3 @@ | ||
let apiCoverage = null; | ||
let projectRoot = null; | ||
class Helper { | ||
@@ -51,13 +49,2 @@ /** | ||
/** | ||
* @return {string} | ||
*/ | ||
static projectRoot() { | ||
if (!projectRoot) { | ||
// Project root will be different for node6-transpiled code. | ||
projectRoot = fs.existsSync(path.join(__dirname, '..', 'package.json')) ? path.join(__dirname, '..') : path.join(__dirname, '..', '..'); | ||
} | ||
return projectRoot; | ||
} | ||
/** | ||
* @param {!Protocol.Runtime.ExceptionDetails} exceptionDetails | ||
@@ -64,0 +51,0 @@ * @return {string} |
@@ -41,3 +41,3 @@ /** | ||
* @param {string} key | ||
* @param {{text: string}=} options | ||
* @param {{text?: string}=} options | ||
*/ | ||
@@ -44,0 +44,0 @@ /* async */ down(key, options = { text: undefined }) {return (fn => { |
@@ -25,4 +25,3 @@ /** | ||
const fs = require('fs'); | ||
const {helper, assert, debugError} = require('./helper'); | ||
const ChromiumRevision = require(path.join(helper.projectRoot(), 'package.json')).puppeteer.chromium_revision; | ||
const {helper, debugError} = require('./helper'); | ||
const {TimeoutError} = require('./Errors'); | ||
@@ -60,6 +59,17 @@ | ||
/** | ||
* @param {string} projectRoot | ||
* @param {string} preferredRevision | ||
* @param {boolean} isPuppeteerCore | ||
*/ | ||
constructor(projectRoot, preferredRevision, isPuppeteerCore) { | ||
this._projectRoot = projectRoot; | ||
this._preferredRevision = preferredRevision; | ||
this._isPuppeteerCore = isPuppeteerCore; | ||
} | ||
/** | ||
* @param {!(LaunchOptions & ChromeArgOptions & BrowserOptions)=} options | ||
* @return {!Promise<!Browser>} | ||
*/ | ||
static /* async */ launch(options = {}) {return (fn => { | ||
/* async */ launch(options = {}) {return (fn => { | ||
const gen = fn.call(this); | ||
@@ -126,6 +136,6 @@ return new Promise((resolve, reject) => { | ||
if (!executablePath) { | ||
const browserFetcher = new BrowserFetcher(); | ||
const revisionInfo = browserFetcher.revisionInfo(ChromiumRevision); | ||
assert(revisionInfo.local, `Chromium revision is not downloaded. Run "npm install" or "yarn install"`); | ||
chromeExecutable = revisionInfo.executablePath; | ||
const {missingText, executablePath} = this._resolveExecutablePath(); | ||
if (missingText) | ||
throw new Error(missingText); | ||
chromeExecutable = executablePath; | ||
} | ||
@@ -179,3 +189,3 @@ | ||
if (!usePipe) { | ||
const browserWSEndpoint = (yield waitForWSEndpoint(chromeProcess, timeout)); | ||
const browserWSEndpoint = (yield waitForWSEndpoint(chromeProcess, timeout, this._preferredRevision)); | ||
connection = (yield Connection.createForWebSocket(browserWSEndpoint, slowMo)); | ||
@@ -280,3 +290,3 @@ } else { | ||
*/ | ||
static defaultArgs(options = {}) { | ||
defaultArgs(options = {}) { | ||
const { | ||
@@ -311,13 +321,11 @@ devtools = false, | ||
*/ | ||
static executablePath() { | ||
const browserFetcher = new BrowserFetcher(); | ||
const revisionInfo = browserFetcher.revisionInfo(ChromiumRevision); | ||
return revisionInfo.executablePath; | ||
executablePath() { | ||
return this._resolveExecutablePath().executablePath; | ||
} | ||
/** | ||
* @param {!(BrowserOptions & {browserWSEndpoint: string})=} options | ||
* @param {!(BrowserOptions & {browserWSEndpoint: string})} options | ||
* @return {!Promise<!Browser>} | ||
*/ | ||
static /* async */ connect(options) {return (fn => { | ||
/* async */ connect(options) {return (fn => { | ||
const gen = fn.call(this); | ||
@@ -359,2 +367,27 @@ return new Promise((resolve, reject) => { | ||
});} | ||
/** | ||
* @return {{executablePath: string, missingText: ?string}} | ||
*/ | ||
_resolveExecutablePath() { | ||
const browserFetcher = new BrowserFetcher(this._projectRoot); | ||
// puppeteer-core doesn't take into account PUPPETEER_* env variables. | ||
if (!this._isPuppeteerCore) { | ||
const executablePath = process.env['PUPPETEER_EXECUTABLE_PATH']; | ||
if (executablePath) { | ||
const missingText = !fs.existsSync(executablePath) ? 'Tried to use PUPPETEER_EXECUTABLE_PATH env variable to launch browser but did not find any executable at: ' + executablePath : null; | ||
return { executablePath, missingText }; | ||
} | ||
const revision = process.env['PUPPETEER_CHROMIUM_REVISION']; | ||
if (revision) { | ||
const revisionInfo = browserFetcher.revisionInfo(revision); | ||
const missingText = !revisionInfo.local ? 'Tried to use PUPPETEER_CHROMIUM_REVISION env variable to launch browser but did not find executable at: ' + revisionInfo.executablePath : null; | ||
return {executablePath: revisionInfo.executablePath, missingText}; | ||
} | ||
} | ||
const revisionInfo = browserFetcher.revisionInfo(this._preferredRevision); | ||
const missingText = !revisionInfo.local ? `Chromium revision is not downloaded. Run "npm install" or "yarn install"` : null; | ||
return {executablePath: revisionInfo.executablePath, missingText}; | ||
} | ||
} | ||
@@ -365,5 +398,6 @@ | ||
* @param {number} timeout | ||
* @param {string} preferredRevision | ||
* @return {!Promise<string>} | ||
*/ | ||
function waitForWSEndpoint(chromeProcess, timeout) { | ||
function waitForWSEndpoint(chromeProcess, timeout, preferredRevision) { | ||
return new Promise((resolve, reject) => { | ||
@@ -396,3 +430,3 @@ const rl = readline.createInterface({ input: chromeProcess.stderr }); | ||
cleanup(); | ||
reject(new TimeoutError(`Timed out after ${timeout} ms while trying to connect to Chrome! The only Chrome revision guaranteed to work is r${ChromiumRevision}`)); | ||
reject(new TimeoutError(`Timed out after ${timeout} ms while trying to connect to Chrome! The only Chrome revision guaranteed to work is r${preferredRevision}`)); | ||
} | ||
@@ -399,0 +433,0 @@ |
@@ -54,12 +54,11 @@ /** | ||
const lifecycleCompletePromise = new Promise(fulfill => { | ||
this._lifecycleCompleteCallback = fulfill; | ||
this._sameDocumentNavigationPromise = new Promise(fulfill => { | ||
this._sameDocumentNavigationCompleteCallback = fulfill; | ||
}); | ||
this._navigationPromise = Promise.race([ | ||
this._createTimeoutPromise(), | ||
lifecycleCompletePromise | ||
]).then(error => { | ||
this._cleanup(); | ||
return error; | ||
this._newDocumentNavigationPromise = new Promise(fulfill => { | ||
this._newDocumentNavigationCompleteCallback = fulfill; | ||
}); | ||
this._timeoutPromise = this._createTimeoutPromise(); | ||
} | ||
@@ -70,2 +69,23 @@ | ||
*/ | ||
sameDocumentNavigationPromise() { | ||
return this._sameDocumentNavigationPromise; | ||
} | ||
/** | ||
* @return {!Promise<?Error>} | ||
*/ | ||
newDocumentNavigationPromise() { | ||
return this._newDocumentNavigationPromise; | ||
} | ||
/** | ||
* @return {!Promise<?Error>} | ||
*/ | ||
timeoutPromise() { | ||
return this._timeoutPromise; | ||
} | ||
/** | ||
* @return {!Promise<?Error>} | ||
*/ | ||
_createTimeoutPromise() { | ||
@@ -80,35 +100,2 @@ if (!this._timeout) | ||
/** | ||
* @return {!Promise<?Error>} | ||
*/ | ||
/* async */ navigationPromise() {return (fn => { | ||
const gen = fn.call(this); | ||
return new Promise((resolve, reject) => { | ||
function step(key, arg) { | ||
let info, value; | ||
try { | ||
info = gen[key](arg); | ||
value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
return Promise.resolve(value).then( | ||
value => { | ||
step('next', value); | ||
}, | ||
err => { | ||
step('throw', err); | ||
}); | ||
} | ||
} | ||
return step('next'); | ||
}); | ||
})(function*(){ | ||
return this._navigationPromise; | ||
});} | ||
/** | ||
* @param {!Puppeteer.Frame} frame | ||
@@ -129,3 +116,6 @@ */ | ||
return; | ||
this._lifecycleCompleteCallback(); | ||
if (this._hasSameDocumentNavigation) | ||
this._sameDocumentNavigationCompleteCallback(); | ||
if (this._frame._loaderId !== this._initialLoaderId) | ||
this._newDocumentNavigationCompleteCallback(); | ||
@@ -150,9 +140,4 @@ /** | ||
cancel() { | ||
this._cleanup(); | ||
} | ||
_cleanup() { | ||
dispose() { | ||
helper.removeEventListeners(this._eventListeners); | ||
this._lifecycleCompleteCallback(new Error('Navigation failed')); | ||
clearTimeout(this._maximumTimer); | ||
@@ -159,0 +144,0 @@ } |
@@ -351,10 +351,13 @@ /** | ||
if (request) { | ||
this._handleRequestRedirect(request, event.redirectResponse.status, event.redirectResponse.headers, event.redirectResponse.fromDiskCache, event.redirectResponse.fromServiceWorker, event.redirectResponse.securityDetails); | ||
this._handleRequestRedirect(request, event.redirectResponse); | ||
redirectChain = request._redirectChain; | ||
} | ||
} | ||
const isNavigationRequest = event.requestId === event.loaderId && event.type === 'Document'; | ||
this._handleRequestStart(event.requestId, interceptionId, event.request.url, isNavigationRequest, event.type, event.request, event.frameId, redirectChain); | ||
const frame = event.frameId ? this._frameManager.frame(event.frameId) : null; | ||
const request = new Request(this._client, frame, interceptionId, this._userRequestInterceptionEnabled, event, redirectChain); | ||
this._requestIdToRequest.set(event.requestId, request); | ||
this.emit(NetworkManager.Events.Request, request); | ||
} | ||
/** | ||
@@ -371,10 +374,6 @@ * @param {!Protocol.Network.requestServedFromCachePayload} event | ||
* @param {!Request} request | ||
* @param {number} redirectStatus | ||
* @param {!Object} redirectHeaders | ||
* @param {boolean} fromDiskCache | ||
* @param {boolean} fromServiceWorker | ||
* @param {?Object} securityDetails | ||
* @param {!Protocol.Network.Response} responsePayload | ||
*/ | ||
_handleRequestRedirect(request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails) { | ||
const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails); | ||
_handleRequestRedirect(request, responsePayload) { | ||
const response = new Response(this._client, request, responsePayload); | ||
request._response = response; | ||
@@ -390,21 +389,2 @@ request._redirectChain.push(request); | ||
/** | ||
* @param {string} requestId | ||
* @param {?string} interceptionId | ||
* @param {string} url | ||
* @param {boolean} isNavigationRequest | ||
* @param {string} resourceType | ||
* @param {!Protocol.Network.Request} requestPayload | ||
* @param {?string} frameId | ||
* @param {!Array<!Request>} redirectChain | ||
*/ | ||
_handleRequestStart(requestId, interceptionId, url, isNavigationRequest, resourceType, requestPayload, frameId, redirectChain) { | ||
let frame = null; | ||
if (frameId) | ||
frame = this._frameManager.frame(frameId); | ||
const request = new Request(this._client, requestId, interceptionId, isNavigationRequest, this._userRequestInterceptionEnabled, url, resourceType, requestPayload, frame, redirectChain); | ||
this._requestIdToRequest.set(requestId, request); | ||
this.emit(NetworkManager.Events.Request, request); | ||
} | ||
/** | ||
* @param {!Protocol.Network.responseReceivedPayload} event | ||
@@ -417,4 +397,3 @@ */ | ||
return; | ||
const response = new Response(this._client, request, event.response.status, event.response.headers, | ||
event.response.fromDiskCache, event.response.fromServiceWorker, event.response.securityDetails); | ||
const response = new Response(this._client, request, event.response); | ||
request._response = response; | ||
@@ -461,16 +440,12 @@ this.emit(NetworkManager.Events.Response, response); | ||
* @param {!Puppeteer.CDPSession} client | ||
* @param {?string} requestId | ||
* @param {?Puppeteer.Frame} frame | ||
* @param {string} interceptionId | ||
* @param {boolean} isNavigationRequest | ||
* @param {boolean} allowInterception | ||
* @param {string} url | ||
* @param {string} resourceType | ||
* @param {!Protocol.Network.Request} payload | ||
* @param {?Puppeteer.Frame} frame | ||
* @param {!Protocol.Network.requestWillBeSentPayload} event | ||
* @param {!Array<!Request>} redirectChain | ||
*/ | ||
constructor(client, requestId, interceptionId, isNavigationRequest, allowInterception, url, resourceType, payload, frame, redirectChain) { | ||
constructor(client, frame, interceptionId, allowInterception, event, redirectChain) { | ||
this._client = client; | ||
this._requestId = requestId; | ||
this._isNavigationRequest = isNavigationRequest; | ||
this._requestId = event.requestId; | ||
this._isNavigationRequest = event.requestId === event.loaderId && event.type === 'Document'; | ||
this._interceptionId = interceptionId; | ||
@@ -482,11 +457,11 @@ this._allowInterception = allowInterception; | ||
this._url = url; | ||
this._resourceType = resourceType.toLowerCase(); | ||
this._method = payload.method; | ||
this._postData = payload.postData; | ||
this._url = event.request.url; | ||
this._resourceType = event.type.toLowerCase(); | ||
this._method = event.request.method; | ||
this._postData = event.request.postData; | ||
this._headers = {}; | ||
this._frame = frame; | ||
this._redirectChain = redirectChain; | ||
for (const key of Object.keys(payload.headers)) | ||
this._headers[key.toLowerCase()] = payload.headers[key]; | ||
for (const key of Object.keys(event.request.headers)) | ||
this._headers[key.toLowerCase()] = event.request.headers[key]; | ||
@@ -518,3 +493,3 @@ this._fromMemoryCache = false; | ||
/** | ||
* @return {string} | ||
* @return {string|undefined} | ||
*/ | ||
@@ -760,9 +735,5 @@ postData() { | ||
* @param {!Request} request | ||
* @param {number} status | ||
* @param {!Object} headers | ||
* @param {boolean} fromDiskCache | ||
* @param {boolean} fromServiceWorker | ||
* @param {?Object} securityDetails | ||
* @param {!Protocol.Network.Response} responsePayload | ||
*/ | ||
constructor(client, request, status, headers, fromDiskCache, fromServiceWorker, securityDetails) { | ||
constructor(client, request, responsePayload) { | ||
this._client = client; | ||
@@ -776,21 +747,25 @@ this._request = request; | ||
this._status = status; | ||
this._remoteAddress = { | ||
ip: responsePayload.remoteIPAddress, | ||
port: responsePayload.remotePort, | ||
}; | ||
this._status = responsePayload.status; | ||
this._statusText = responsePayload.statusText; | ||
this._url = request.url(); | ||
this._fromDiskCache = fromDiskCache; | ||
this._fromServiceWorker = fromServiceWorker; | ||
this._fromDiskCache = !!responsePayload.fromDiskCache; | ||
this._fromServiceWorker = !!responsePayload.fromServiceWorker; | ||
this._headers = {}; | ||
for (const key of Object.keys(headers)) | ||
this._headers[key.toLowerCase()] = headers[key]; | ||
this._securityDetails = null; | ||
if (securityDetails) { | ||
this._securityDetails = new SecurityDetails( | ||
securityDetails['subjectName'], | ||
securityDetails['issuer'], | ||
securityDetails['validFrom'], | ||
securityDetails['validTo'], | ||
securityDetails['protocol']); | ||
} | ||
for (const key of Object.keys(responsePayload.headers)) | ||
this._headers[key.toLowerCase()] = responsePayload.headers[key]; | ||
this._securityDetails = responsePayload.securityDetails ? new SecurityDetails(responsePayload.securityDetails) : null; | ||
} | ||
/** | ||
* @return {{ip: string, port: number}} | ||
*/ | ||
remoteAddress() { | ||
return this._remoteAddress; | ||
} | ||
/** | ||
* @return {string} | ||
@@ -817,2 +792,9 @@ */ | ||
/** | ||
* @return {string} | ||
*/ | ||
statusText() { | ||
return this._statusText; | ||
} | ||
/** | ||
* @return {!Object} | ||
@@ -1001,15 +983,10 @@ */ | ||
/** | ||
* @param {string} subjectName | ||
* @param {string} issuer | ||
* @param {number} validFrom | ||
* @param {number} validTo | ||
* @param {string} protocol | ||
* @param {!Protocol.Network.SecurityDetails} securityPayload | ||
*/ | ||
constructor(subjectName, issuer, validFrom, validTo, protocol) { | ||
this._subjectName = subjectName; | ||
this._issuer = issuer; | ||
this._validFrom = validFrom; | ||
this._validTo = validTo; | ||
this._protocol = protocol; | ||
constructor(securityPayload) { | ||
this._subjectName = securityPayload['subjectName']; | ||
this._issuer = securityPayload['issuer']; | ||
this._validFrom = securityPayload['validFrom']; | ||
this._validTo = securityPayload['validTo']; | ||
this._protocol = securityPayload['protocol']; | ||
} | ||
@@ -1016,0 +993,0 @@ |
@@ -22,7 +22,17 @@ /** | ||
/** | ||
* @param {string} projectRoot | ||
* @param {string} preferredRevision | ||
* @param {boolean} isPuppeteerCore | ||
*/ | ||
constructor(projectRoot, preferredRevision, isPuppeteerCore) { | ||
this._projectRoot = projectRoot; | ||
this._launcher = new Launcher(projectRoot, preferredRevision, isPuppeteerCore); | ||
} | ||
/** | ||
* @param {!Object=} options | ||
* @return {!Promise<!Puppeteer.Browser>} | ||
*/ | ||
static launch(options) { | ||
return Launcher.launch(options); | ||
launch(options) { | ||
return this._launcher.launch(options); | ||
} | ||
@@ -34,4 +44,4 @@ | ||
*/ | ||
static connect(options) { | ||
return Launcher.connect(options); | ||
connect(options) { | ||
return this._launcher.connect(options); | ||
} | ||
@@ -42,4 +52,4 @@ | ||
*/ | ||
static executablePath() { | ||
return Launcher.executablePath(); | ||
executablePath() { | ||
return this._launcher.executablePath(); | ||
} | ||
@@ -50,4 +60,4 @@ | ||
*/ | ||
static defaultArgs(options) { | ||
return Launcher.defaultArgs(options); | ||
defaultArgs(options) { | ||
return this._launcher.defaultArgs(options); | ||
} | ||
@@ -59,4 +69,4 @@ | ||
*/ | ||
static createBrowserFetcher(options) { | ||
return new BrowserFetcher(options); | ||
createBrowserFetcher(options) { | ||
return new BrowserFetcher(this._projectRoot, options); | ||
} | ||
@@ -63,0 +73,0 @@ }; |
@@ -106,3 +106,3 @@ const {Page} = require('./Page'); | ||
/** | ||
* @return {Puppeteer.Target} | ||
* @return {?Puppeteer.Target} | ||
*/ | ||
@@ -109,0 +109,0 @@ opener() { |
@@ -62,3 +62,3 @@ /** | ||
jsHandleFactory = remoteObject => new JSHandle(executionContext, client, remoteObject); | ||
const executionContext = new ExecutionContext(client, event.context, jsHandleFactory, null); | ||
const executionContext = new ExecutionContext(client, event.context, null); | ||
this._executionContextCallback(executionContext); | ||
@@ -65,0 +65,0 @@ });}); |
{ | ||
"name": "puppeteer-core", | ||
"version": "1.7.0", | ||
"version": "1.8.0", | ||
"description": "A high-level API to control headless Chrome over the DevTools Protocol", | ||
@@ -11,3 +11,3 @@ "main": "index.js", | ||
"puppeteer": { | ||
"chromium_revision": "579032" | ||
"chromium_revision": "588429" | ||
}, | ||
@@ -14,0 +14,0 @@ "scripts": { |
@@ -9,3 +9,3 @@ # Puppeteer | ||
###### [API](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md) | [FAQ](#faq) | [Contributing](https://github.com/GoogleChrome/puppeteer/blob/master/CONTRIBUTING.md) | ||
###### [API](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md) | [FAQ](#faq) | [Contributing](https://github.com/GoogleChrome/puppeteer/blob/master/CONTRIBUTING.md) | ||
@@ -41,4 +41,18 @@ > Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). Puppeteer runs [headless](https://developers.google.com/web/updates/2017/04/headless-chrome) by default, but can be configured to run full (non-headless) Chrome or Chromium. | ||
Note: When you install Puppeteer, it downloads a recent version of Chromium (~170Mb Mac, ~282Mb Linux, ~280Mb Win) that is guaranteed to work with the API. To skip the download, see [Environment variables](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md#environment-variables). | ||
Note: When you install Puppeteer, it downloads a recent version of Chromium (~170MB Mac, ~282MB Linux, ~280MB Win) that is guaranteed to work with the API. To skip the download, see [Environment variables](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#environment-variables). | ||
### puppeteer-core | ||
Since version 1.7.0 we publish the [`puppeteer-core`](https://www.npmjs.com/package/puppeteer-core) package, | ||
a version of Puppeteer that doesn't download Chromium by default. | ||
```bash | ||
npm i puppeteer-core | ||
``` | ||
`puppeteer-core` is intended to be a lightweight version of puppeteer for launching an existing browser installation or for connecting to a remote one. | ||
See [puppeteer vs puppeteer-core](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteer-vs-puppeteer-core). | ||
### Usage | ||
@@ -49,3 +63,3 @@ | ||
Puppeteer will be familiar to people using other browser testing frameworks. You create an instance | ||
of `Browser`, open pages, and then manipulate them with [Puppeteer's API](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md#). | ||
of `Browser`, open pages, and then manipulate them with [Puppeteer's API](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#). | ||
@@ -75,3 +89,3 @@ **Example** - navigating to https://example.com and saving a screenshot as *example.png*: | ||
Puppeteer sets an initial page size to 800px x 600px, which defines the screenshot size. The page size can be customized with [`Page.setViewport()`](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md#pagesetviewportviewport). | ||
Puppeteer sets an initial page size to 800px x 600px, which defines the screenshot size. The page size can be customized with [`Page.setViewport()`](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#pagesetviewportviewport). | ||
@@ -101,3 +115,3 @@ **Example** - create a PDF. | ||
See [`Page.pdf()`](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md#pagepdfoptions) for more information about creating pdfs. | ||
See [`Page.pdf()`](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#pagepdfoptions) for more information about creating pdfs. | ||
@@ -137,3 +151,3 @@ **Example** - evaluate script in the context of the page | ||
See [`Page.evaluate()`](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md#pageevaluatepagefunction-args) for more information on `evaluate` and related methods like `evaluateOnNewDocument` and `exposeFunction`. | ||
See [`Page.evaluate()`](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#pageevaluatepagefunction-args) for more information on `evaluate` and related methods like `evaluateOnNewDocument` and `exposeFunction`. | ||
@@ -147,3 +161,3 @@ <!-- [END getstarted] --> | ||
Puppeteer launches Chromium in [headless mode](https://developers.google.com/web/updates/2017/04/headless-chrome). To launch a full version of Chromium, set the ['headless' option](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md#puppeteerlaunchoptions) when launching a browser: | ||
Puppeteer launches Chromium in [headless mode](https://developers.google.com/web/updates/2017/04/headless-chrome). To launch a full version of Chromium, set the ['headless' option](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#puppeteerlaunchoptions) when launching a browser: | ||
@@ -164,3 +178,3 @@ ```js | ||
See [`Puppeteer.launch()`](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md#puppeteerlaunchoptions) for more information. | ||
See [`Puppeteer.launch()`](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#puppeteerlaunchoptions) for more information. | ||
@@ -175,5 +189,7 @@ See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for a description of the differences between Chromium and Chrome. [`This article`](https://chromium.googlesource.com/chromium/src/+/lkcr/docs/chromium_browser_vs_google_chrome.md) describes some differences for Linux users. | ||
## API Documentation | ||
## Resources | ||
Explore the [API documentation](docs/api.md) and [examples](https://github.com/GoogleChrome/puppeteer/tree/master/examples/) to learn more. | ||
- [API Documentation](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md) | ||
- [Examples](https://github.com/GoogleChrome/puppeteer/tree/master/examples/) | ||
- [Community list of Puppeteer resources](https://github.com/transitive-bullshit/awesome-puppeteer) | ||
@@ -328,3 +344,3 @@ <!-- [START debugging] --> | ||
* Puppeteer is bundled with Chromium--not Chrome--and so by default, it inherits all of [Chromium's media-related limitations](https://www.chromium.org/audio-video). This means that Puppeteer does not support licensed formats such as AAC or H.264. (However, it is possible to force Puppeteer to use a separately-installed version Chrome instead of Chromium via the [`executablePath` option to `puppeteer.launch`](https://github.com/GoogleChrome/puppeteer/blob/v1.7.0/docs/api.md#puppeteerlaunchoptions). You should only use this configuration if you need an official release of Chrome that supports these media formats.) | ||
* Puppeteer is bundled with Chromium--not Chrome--and so by default, it inherits all of [Chromium's media-related limitations](https://www.chromium.org/audio-video). This means that Puppeteer does not support licensed formats such as AAC or H.264. (However, it is possible to force Puppeteer to use a separately-installed version Chrome instead of Chromium via the [`executablePath` option to `puppeteer.launch`](https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#puppeteerlaunchoptions). You should only use this configuration if you need an official release of Chrome that supports these media formats.) | ||
* Since Puppeteer (in all configurations) controls a desktop version of Chromium/Chrome, features that are only supported by the mobile version of Chrome are not supported. This means that Puppeteer [does not support HTTP Live Streaming (HLS)](https://caniuse.com/#feat=http-live-streaming). | ||
@@ -331,0 +347,0 @@ |
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 2 instances in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
612461
18134
362
35
55
15