chore: use Google's TS style guide's format config (#8542)

This commit is contained in:
jrandolf 2022-06-22 15:25:44 +02:00 committed by GitHub
parent 3744c2f584
commit 84712cbc28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
122 changed files with 2891 additions and 2962 deletions

1
.prettierrc.cjs Normal file
View File

@ -0,0 +1 @@
module.exports = require('gts/.prettierrc.json');

View File

@ -218,7 +218,7 @@ Puppeteer creates its own browser user profile which it **cleans up on every run
This is also handy when debugging code in `page.evaluate()`:
```js
page.on('console', (msg) => console.log('PAGE LOG:', msg.text()));
page.on('console', msg => console.log('PAGE LOG:', msg.text()));
await page.evaluate(() => console.log(`url is ${location.href}`));
```

View File

@ -515,7 +515,7 @@ const puppeteer = require('puppeteer');
],
});
const backgroundPageTarget = await browser.waitForTarget(
(target) => target.type() === 'background_page'
target => target.type() === 'background_page'
);
const backgroundPage = await backgroundPageTarget.page();
// Test the background page as you would any other page.
@ -1003,7 +1003,7 @@ An example of finding a target for a page opened via `window.open`:
```js
await page.evaluate(() => window.open('https://www.example.com/'));
const newWindowTarget = await browser.waitForTarget(
(target) => target.url() === 'https://www.example.com/'
target => target.url() === 'https://www.example.com/'
);
```
@ -1155,7 +1155,7 @@ An example of finding a target for a page opened via `window.open`:
```js
await page.evaluate(() => window.open('https://www.example.com/'));
const newWindowTarget = await browserContext.waitForTarget(
(target) => target.url() === 'https://www.example.com/'
target => target.url() === 'https://www.example.com/'
);
```
@ -1215,7 +1215,7 @@ The arguments passed into `console.log` appear as arguments on the event handler
An example of handling `console` event:
```js
page.on('console', (msg) => {
page.on('console', msg => {
for (let i = 0; i < msg.args().length; ++i)
console.log(`${i}: ${msg.args()[i]}`);
});
@ -1286,14 +1286,14 @@ Emitted when the page opens a new tab or window.
```js
const [popup] = await Promise.all([
new Promise((resolve) => page.once('popup', resolve)),
new Promise(resolve => page.once('popup', resolve)),
page.click('a[target=_blank]'),
]);
```
```js
const [popup] = await Promise.all([
new Promise((resolve) => page.once('popup', resolve)),
new Promise(resolve => page.once('popup', resolve)),
page.evaluate(() => window.open('https://example.com')),
]);
```
@ -1369,12 +1369,12 @@ If `pageFunction` returns a [Promise], then `page.$$eval` would wait for the pro
Examples:
```js
const divCount = await page.$$eval('div', (divs) => divs.length);
const divCount = await page.$$eval('div', divs => divs.length);
```
```js
const options = await page.$$eval('div > span.options', (options) =>
options.map((option) => option.textContent)
const options = await page.$$eval('div > span.options', options =>
options.map(option => option.textContent)
);
```
@ -1392,9 +1392,9 @@ If `pageFunction` returns a [Promise], then `page.$eval` would wait for the prom
Examples:
```js
const searchValue = await page.$eval('#search', (el) => el.value);
const preloadHref = await page.$eval('link[rel=preload]', (el) => el.href);
const html = await page.$eval('.main-container', (e) => e.outerHTML);
const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const html = await page.$eval('.main-container', e => e.outerHTML);
```
Shortcut for [page.mainFrame().$eval(selector, pageFunction)](#frameevalselector-pagefunction-args).
@ -1799,7 +1799,7 @@ If the function passed to the `page.evaluate` returns a non-[Serializable] value
Passing arguments to `pageFunction`:
```js
const result = await page.evaluate((x) => {
const result = await page.evaluate(x => {
return Promise.resolve(8 * x);
}, 7);
console.log(result); // prints "56"
@ -1817,7 +1817,7 @@ console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
```js
const bodyHandle = await page.$('body');
const html = await page.evaluate((body) => body.innerHTML, bodyHandle);
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();
```
@ -1843,10 +1843,7 @@ const aHandle = await page.evaluateHandle('document'); // Handle for the 'docume
```js
const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(
(body) => body.innerHTML,
aHandle
);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
```
@ -1915,8 +1912,8 @@ const crypto = require('crypto');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', (msg) => console.log(msg.text()));
await page.exposeFunction('md5', (text) =>
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('md5', text =>
crypto.createHash('md5').update(text).digest('hex')
);
await page.evaluate(async () => {
@ -1938,8 +1935,8 @@ const fs = require('fs');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', (msg) => console.log(msg.text()));
await page.exposeFunction('readfile', async (filePath) => {
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('readfile', async filePath => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, text) => {
if (err) reject(err);
@ -2180,7 +2177,7 @@ const mapPrototype = await page.evaluateHandle(() => Map.prototype);
// Query all map instances into an array
const mapInstances = await page.queryObjects(mapPrototype);
// Count amount of map objects in heap
const count = await page.evaluate((maps) => maps.length, mapInstances);
const count = await page.evaluate(maps => maps.length, mapInstances);
await mapInstances.dispose();
await mapPrototype.dispose();
```
@ -2380,7 +2377,7 @@ const puppeteer = require('puppeteer');
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
if (interceptedRequest.isInterceptResolutionHandled()) return;
if (
interceptedRequest.url().endsWith('.png') ||
@ -2411,7 +2408,7 @@ This example demonstrates two synchronous handlers working together:
/*
This first handler will succeed in calling request.continue because the request interception has never been resolved.
*/
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
if (interceptedRequest.isInterceptResolutionHandled()) return;
interceptedRequest.continue();
});
@ -2420,7 +2417,7 @@ page.on('request', (interceptedRequest) => {
This second handler will return before calling request.abort because request.continue was already
called by the first handler.
*/
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
if (interceptedRequest.isInterceptResolutionHandled()) return;
interceptedRequest.abort();
});
@ -2432,12 +2429,12 @@ This example demonstrates asynchronous handlers working together:
/*
This first handler will succeed in calling request.continue because the request interception has never been resolved.
*/
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
// The interception has not been handled yet. Control will pass through this guard.
if (interceptedRequest.isInterceptResolutionHandled()) return;
// It is not strictly necessary to return a promise, but doing so will allow Puppeteer to await this handler.
return new Promise((resolve) => {
return new Promise(resolve => {
// Continue after 500ms
setTimeout(() => {
// Inside, check synchronously to verify that the intercept wasn't handled already.
@ -2451,7 +2448,7 @@ page.on('request', (interceptedRequest) => {
}, 500);
});
});
page.on('request', async (interceptedRequest) => {
page.on('request', async interceptedRequest => {
// The interception has not been handled yet. Control will pass through this guard.
if (interceptedRequest.isInterceptResolutionHandled()) return;
@ -2471,13 +2468,13 @@ Here is the example above rewritten using `request.interceptResolutionState`
/*
This first handler will succeed in calling request.continue because the request interception has never been resolved.
*/
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
// The interception has not been handled yet. Control will pass through this guard.
const {action} = interceptedRequest.interceptResolutionState();
if (action === InterceptResolutionAction.AlreadyHandled) return;
// It is not strictly necessary to return a promise, but doing so will allow Puppeteer to await this handler.
return new Promise((resolve) => {
return new Promise(resolve => {
// Continue after 500ms
setTimeout(() => {
// Inside, check synchronously to verify that the intercept wasn't handled already.
@ -2492,7 +2489,7 @@ page.on('request', (interceptedRequest) => {
}, 500);
});
});
page.on('request', async (interceptedRequest) => {
page.on('request', async interceptedRequest => {
// The interception has not been handled yet. Control will pass through this guard.
if (
interceptedRequest.interceptResolutionState().action ===
@ -2534,13 +2531,13 @@ In this example, Legacy Mode prevails and the request is aborted immediately bec
```ts
// Final outcome: immediate abort()
page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Legacy Mode: interception is aborted immediately.
request.abort('failed');
});
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Control will never reach this point because the request was already aborted in Legacy Mode
@ -2554,13 +2551,13 @@ In this example, Legacy Mode prevails and the request is continued because at le
```ts
// Final outcome: immediate continue()
page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to abort at priority 0.
request.abort('failed', 0);
});
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Control reaches this point because the request was cooperatively aborted which postpones resolution.
@ -2571,7 +2568,7 @@ page.on('request', (request) => {
// Legacy Mode: intercept continues immediately.
request.continue({});
});
page.on('request', (request) => {
page.on('request', request => {
// { action: InterceptResolutionAction.AlreadyHandled }, because continue in Legacy Mode was called
console.log(request.interceptResolutionState());
});
@ -2582,19 +2579,19 @@ In this example, Cooperative Intercept Mode is active because all handlers speci
```ts
// Final outcome: cooperative continue() @ 5
page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to abort at priority 10
request.abort('failed', 0);
});
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to continue at priority 5
request.continue(request.continueRequestOverrides(), 5);
});
page.on('request', (request) => {
page.on('request', request => {
// { action: InterceptResolutionAction.Continue, priority: 5 }, because continue @ 5 > abort @ 0
console.log(request.interceptResolutionState());
});
@ -2605,31 +2602,31 @@ In this example, Cooperative Intercept Mode is active because all handlers speci
```ts
// Final outcome: cooperative respond() @ 15
page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to abort at priority 10
request.abort('failed', 10);
});
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to continue at priority 15
request.continue(request.continueRequestOverrides(), 15);
});
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to respond at priority 15
request.respond(request.responseForRequest(), 15);
});
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to respond at priority 12
request.respond(request.responseForRequest(), 12);
});
page.on('request', (request) => {
page.on('request', request => {
// { action: InterceptResolutionAction.Respond, priority: 15 }, because respond @ 15 > continue @ 15 > respond @ 12 > abort @ 10
console.log(request.interceptResolutionState());
});
@ -2656,7 +2653,7 @@ To summarize, reason through whether your use of `request.continue` is just mean
If you are package maintainer and your package uses intercept handlers, you can update your intercept handlers to use Cooperative Intercept Mode. Suppose you have the following existing handler:
```ts
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
if (request.isInterceptResolutionHandled()) return;
if (
interceptedRequest.url().endsWith('.png') ||
@ -2670,7 +2667,7 @@ page.on('request', (interceptedRequest) => {
To use Cooperative Intercept Mode, upgrade `continue()` and `abort()`:
```ts
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
if (request.isInterceptResolutionHandled()) return;
if (
interceptedRequest.url().endsWith('.png') ||
@ -2706,7 +2703,7 @@ export const setInterceptResolutionConfig = (priority = 0) =>
* Note that this handler uses `DEFAULT_INTERCEPT_RESOLUTION_PRIORITY` to "pass" on this request. It is important to use
* the default priority when your handler has no opinion on the request and the intent is to continue() by default.
*/
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
if (request.isInterceptResolutionHandled()) return;
if (
interceptedRequest.url().endsWith('.png') ||
@ -2744,7 +2741,7 @@ export const setInterceptResolutionConfig = (
config: InterceptResolutionConfig
) => (_config = {...DEFAULT_CONFIG, ...config});
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
if (request.isInterceptResolutionHandled()) return;
if (
interceptedRequest.url().endsWith('.png') ||
@ -2931,7 +2928,7 @@ To pass arguments from node.js to the predicate of `page.waitFor` function:
```js
const selector = '.foo';
await page.waitFor(
(selector) => !!document.querySelector(selector),
selector => !!document.querySelector(selector),
{},
selector
);
@ -2970,7 +2967,7 @@ await fileChooser.accept(['/tmp/myfile.pdf']);
- returns: <[Promise]<[Frame]>> Promise which resolves to the matched frame.
```js
const frame = await page.waitForFrame(async (frame) => {
const frame = await page.waitForFrame(async frame => {
return frame.name() === 'Test';
});
```
@ -3006,7 +3003,7 @@ To pass arguments from node.js to the predicate of `page.waitForFunction` functi
```js
const selector = '.foo';
await page.waitForFunction(
(selector) => !!document.querySelector(selector),
selector => !!document.querySelector(selector),
{},
selector
);
@ -3017,7 +3014,7 @@ The predicate of `page.waitForFunction` can be asynchronous too:
```js
const username = 'github-username';
await page.waitForFunction(
async (username) => {
async username => {
const githubResponse = await fetch(
`https://api.github.com/users/${username}`
);
@ -3083,7 +3080,7 @@ page.waitForNetworkIdle(); // The promise resolves after fetch above finishes
```js
const firstRequest = await page.waitForRequest('http://example.com/resource');
const finalRequest = await page.waitForRequest(
(request) =>
request =>
request.url() === 'http://example.com' && request.method() === 'GET'
);
return firstRequest.url();
@ -3101,10 +3098,10 @@ const firstResponse = await page.waitForResponse(
'https://example.com/resource'
);
const finalResponse = await page.waitForResponse(
(response) =>
response =>
response.url() === 'https://example.com' && response.status() === 200
);
const finalResponse = await page.waitForResponse(async (response) => {
const finalResponse = await page.waitForResponse(async response => {
return (await response.text()).includes('<html>');
});
return finalResponse.ok();
@ -3228,10 +3225,10 @@ The WebWorker class represents a [WebWorker](https://developer.mozilla.org/en-US
The events `workercreated` and `workerdestroyed` are emitted on the page object to signal the worker lifecycle.
```js
page.on('workercreated', (worker) =>
page.on('workercreated', worker =>
console.log('Worker created: ' + worker.url())
);
page.on('workerdestroyed', (worker) =>
page.on('workerdestroyed', worker =>
console.log('Worker destroyed: ' + worker.url())
);
@ -3708,7 +3705,7 @@ const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('dialog', async (dialog) => {
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.dismiss();
await browser.close();
@ -3804,8 +3801,8 @@ const puppeteer = require('puppeteer');
An example of getting text from an iframe element:
```js
const frame = page.frames().find((frame) => frame.name() === 'myframe');
const text = await frame.$eval('.selector', (element) => element.textContent);
const frame = page.frames().find(frame => frame.name() === 'myframe');
const text = await frame.$eval('.selector', element => element.textContent);
console.log(text);
```
@ -3837,7 +3834,7 @@ If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the pr
Examples:
```js
const divsCounts = await frame.$$eval('div', (divs) => divs.length);
const divsCounts = await frame.$$eval('div', divs => divs.length);
```
#### frame.$eval(selector, pageFunction[, ...args])
@ -3854,9 +3851,9 @@ If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the pro
Examples:
```js
const searchValue = await frame.$eval('#search', (el) => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', (el) => el.href);
const html = await frame.$eval('.main-container', (e) => e.outerHTML);
const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', e => e.outerHTML);
```
#### frame.$x(expression)
@ -3946,7 +3943,7 @@ console.log(await frame.evaluate('1 + 2')); // prints "3"
```js
const bodyHandle = await frame.$('body');
const html = await frame.evaluate((body) => body.innerHTML, bodyHandle);
const html = await frame.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();
```
@ -3978,7 +3975,7 @@ const aHandle = await frame.evaluateHandle('document'); // Handle for the 'docum
```js
const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle(
(body) => body.innerHTML,
body => body.innerHTML,
aHandle
);
console.log(await resultHandle.jsonValue());
@ -4157,7 +4154,7 @@ To pass arguments from node.js to the predicate of `page.waitFor` function:
```js
const selector = '.foo';
await page.waitFor(
(selector) => !!document.querySelector(selector),
selector => !!document.querySelector(selector),
{},
selector
);
@ -4194,7 +4191,7 @@ To pass arguments from node.js to the predicate of `page.waitForFunction` functi
```js
const selector = '.foo';
await page.waitForFunction(
(selector) => !!document.querySelector(selector),
selector => !!document.querySelector(selector),
{},
selector
);
@ -4395,7 +4392,7 @@ const aHandle = await context.evaluateHandle('1 + 2'); // Handle for the '3' obj
```js
const aHandle = await context.evaluateHandle(() => document.body);
const resultHandle = await context.evaluateHandle(
(body) => body.innerHTML,
body => body.innerHTML,
aHandle
);
console.log(await resultHandle.jsonValue()); // prints body's innerHTML
@ -4424,7 +4421,7 @@ const mapPrototype = await page.evaluateHandle(() => Map.prototype);
// Query all map instances into an array
const mapInstances = await page.queryObjects(mapPrototype);
// Count amount of map objects in heap
const count = await page.evaluate((maps) => maps.length, mapInstances);
const count = await page.evaluate(maps => maps.length, mapInstances);
await mapInstances.dispose();
await mapPrototype.dispose();
```
@ -4468,7 +4465,7 @@ Examples:
```js
const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate((node) => node.innerText)).toBe('10');
expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');
```
#### jsHandle.evaluateHandle(pageFunction[, ...args])
@ -4584,7 +4581,7 @@ Examples:
```js
const feedHandle = await page.$('.feed');
expect(
await feedHandle.$$eval('.tweet', (nodes) => nodes.map((n) => n.innerText))
await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))
).toEqual(['Hello!', 'Hi!']);
```
@ -4603,10 +4600,8 @@ Examples:
```js
const tweetHandle = await page.$('.tweet');
expect(await tweetHandle.$eval('.like', (node) => node.innerText)).toBe('100');
expect(await tweetHandle.$eval('.retweets', (node) => node.innerText)).toBe(
'10'
);
expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
```
#### elementHandle.$x(expression)
@ -4740,7 +4735,7 @@ Examples:
```js
const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate((node) => node.innerText)).toBe('10');
expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');
```
#### elementHandle.evaluateHandle(pageFunction[, ...args])
@ -5005,7 +5000,7 @@ your handler has no opinion about it.
```js
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
// Override headers
@ -5044,7 +5039,7 @@ The method returns `null` unless this request was failed, as reported by
Example of logging all failed requests:
```js
page.on('requestfailed', (request) => {
page.on('requestfailed', request => {
console.log(request.url() + ' ' + request.failure().errorText);
});
```
@ -5091,7 +5086,7 @@ This example will `continue()` a request at a slightly higher priority than the
already handled and is not already being continued.
```js
page.on('request', (interceptedRequest) => {
page.on('request', interceptedRequest => {
const {action, priority} = interceptedRequest.interceptResolutionState();
if (action === InterceptResolutionAction.AlreadyHandled) return;
if (action === InterceptResolutionAction.Continue) return;
@ -5180,7 +5175,7 @@ An example of fulfilling all requests with 404 responses:
```js
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
request.respond({

View File

@ -22,7 +22,7 @@ const puppeteer = require('puppeteer');
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.resourceType() === 'image') {
request.abort();
} else {

View File

@ -35,9 +35,9 @@ const firefoxOptions = {
// Extract articles from the page.
const resultsSelector = '.titlelink';
const links = await page.evaluate((resultsSelector) => {
const links = await page.evaluate(resultsSelector => {
const anchors = Array.from(document.querySelectorAll(resultsSelector));
return anchors.map((anchor) => {
return anchors.map(anchor => {
const title = anchor.textContent.trim();
return `${title} - ${anchor.href}`;
});

View File

@ -23,7 +23,7 @@ const puppeteer = require('puppeteer');
const page = await browser.newPage();
// Define a window.onCustomEvent function on the page.
await page.exposeFunction('onCustomEvent', (e) => {
await page.exposeFunction('onCustomEvent', e => {
console.log(`${e.type} fired`, e.detail || '');
});
@ -33,8 +33,8 @@ const puppeteer = require('puppeteer');
* @returns {!Promise}
*/
function listenFor(type) {
return page.evaluateOnNewDocument((type) => {
document.addEventListener(type, (e) => {
return page.evaluateOnNewDocument(type => {
document.addEventListener(type, e => {
window.onCustomEvent({type, detail: e.detail});
});
}, type);

View File

@ -23,7 +23,7 @@ async function attachFrame(frameId, url) {
frame.src = url;
frame.id = frameId;
document.body.appendChild(frame);
await new Promise((x) => {
await new Promise(x => {
return (frame.onload = x);
});
return frame;

View File

@ -42,9 +42,9 @@ const puppeteer = require('puppeteer');
await page.waitForSelector(resultsSelector);
// Extract the results from the page.
const links = await page.evaluate((resultsSelector) => {
const links = await page.evaluate(resultsSelector => {
const anchors = Array.from(document.querySelectorAll(resultsSelector));
return anchors.map((anchor) => {
return anchors.map(anchor => {
const title = anchor.textContent.split('|')[0].trim();
return `${title} - ${anchor.href}`;
});

View File

@ -114,8 +114,9 @@
"eslint-plugin-tsdoc": "0.2.16",
"esprima": "4.0.1",
"expect": "25.2.7",
"gts": "3.1.0",
"husky": "8.0.1",
"jpeg-js": "0.4.3",
"jpeg-js": "0.4.4",
"mime": "3.0.0",
"minimist": "1.2.6",
"mocha": "10.0.0",

View File

@ -1,5 +0,0 @@
module.exports = {
semi: true,
trailingComma: 'es5',
singleQuote: true,
};

View File

@ -32,7 +32,7 @@ if (invalidDeps.size > 0) {
console.error('Found non-pinned dependencies in package.json:');
console.log(
[...invalidDeps.keys()]
.map((k) => {
.map(k => {
return ` ${k}`;
})
.join('\n')

View File

@ -146,18 +146,14 @@ function testProject(folder: string) {
// there was no node_modules folder, which is fine.
}
console.log('===> Installing Puppeteer from tar file', tarLocation);
const { status, stderr, stdout } = spawnSync(
'npm',
['install', tarLocation],
{
const {status, stderr, stdout} = spawnSync('npm', ['install', tarLocation], {
env: {
...process.env,
PUPPETEER_SKIP_DOWNLOAD: '1',
},
cwd: projectLocation,
encoding: 'utf-8',
}
);
});
if (status) {
console.error(
@ -171,7 +167,7 @@ function testProject(folder: string) {
const result = compileAndCatchErrors(projectLocation);
const expectedErrors = EXPECTED_ERRORS.get(folder) || [];
if (
result.tsErrorMesssage.find((line) => {
result.tsErrorMesssage.find(line => {
return line.includes('good.ts') || line.includes('good.js');
})
) {
@ -182,12 +178,12 @@ function testProject(folder: string) {
);
process.exit(1);
}
const errorsInTsMessage = result.tsErrorMesssage.filter((line) => {
const errorsInTsMessage = result.tsErrorMesssage.filter(line => {
return line.includes('bad.ts') || line.includes('bad.js');
});
const expectedErrorsThatHaveOccurred = new Set<string>();
const unexpectedErrors = errorsInTsMessage.filter((message) => {
const isExpected = expectedErrors.some((expectedError) => {
const unexpectedErrors = errorsInTsMessage.filter(message => {
const isExpected = expectedErrors.some(expectedError => {
const isExpected = message.startsWith(expectedError);
if (isExpected) {
expectedErrorsThatHaveOccurred.add(expectedError);
@ -205,7 +201,7 @@ function testProject(folder: string) {
);
process.exit(1);
}
expectedErrors.forEach((expected) => {
expectedErrors.forEach(expected => {
if (!expectedErrorsThatHaveOccurred.has(expected)) {
console.error(
`${projectLocation} expected error that was not thrown: ${expected}`
@ -216,6 +212,6 @@ function testProject(folder: string) {
console.log('===> ✅ Type-checked correctly.');
}
PROJECT_FOLDERS.forEach((folder) => {
PROJECT_FOLDERS.forEach(folder => {
testProject(folder);
});

View File

@ -193,7 +193,7 @@ export class Accessibility {
const defaultRoot = AXNode.createTree(nodes);
let needle: AXNode | null = defaultRoot;
if (backendNodeId) {
needle = defaultRoot.find((node) => {
needle = defaultRoot.find(node => {
return node.payload.backendDOMNodeId === backendNodeId;
});
if (!needle) {

View File

@ -132,7 +132,7 @@ const queryAll = async (
const {name, role} = parseAriaSelector(selector);
const res = await queryAXTree(exeCtx._client, element, name, role);
return Promise.all(
res.map((axNode) => {
res.map(axNode => {
return exeCtx._adoptBackendNodeId(axNode.backendDOMNodeId);
})
);

View File

@ -548,7 +548,7 @@ export class Browser extends EventEmitter {
* an array with all the targets in all browser contexts.
*/
targets(): Target[] {
return Array.from(this.#targets.values()).filter((target) => {
return Array.from(this.#targets.values()).filter(target => {
return target._isInitialized;
});
}
@ -557,7 +557,7 @@ export class Browser extends EventEmitter {
* The target associated with the browser.
*/
target(): Target {
const browserTarget = this.targets().find((target) => {
const browserTarget = this.targets().find(target => {
return target.type() === 'browser';
});
if (!browserTarget) {
@ -587,7 +587,7 @@ export class Browser extends EventEmitter {
const {timeout = 30000} = options;
let resolve: (value: Target | PromiseLike<Target>) => void;
let isResolved = false;
const targetPromise = new Promise<Target>((x) => {
const targetPromise = new Promise<Target>(x => {
return (resolve = x);
});
this.on(BrowserEmittedEvents.TargetCreated, check);
@ -622,7 +622,7 @@ export class Browser extends EventEmitter {
*/
async pages(): Promise<Page[]> {
const contextPages = await Promise.all(
this.browserContexts().map((context) => {
this.browserContexts().map(context => {
return context.pages();
})
);
@ -762,7 +762,7 @@ export class BrowserContext extends EventEmitter {
* An array of all active targets inside the browser context.
*/
targets(): Target[] {
return this.#browser.targets().filter((target) => {
return this.#browser.targets().filter(target => {
return target.browserContext() === this;
});
}
@ -788,7 +788,7 @@ export class BrowserContext extends EventEmitter {
predicate: (x: Target) => boolean | Promise<boolean>,
options: {timeout?: number} = {}
): Promise<Target> {
return this.#browser.waitForTarget((target) => {
return this.#browser.waitForTarget(target => {
return target.browserContext() === this && predicate(target);
}, options);
}
@ -803,7 +803,7 @@ export class BrowserContext extends EventEmitter {
async pages(): Promise<Page[]> {
const pages = await Promise.all(
this.targets()
.filter((target) => {
.filter(target => {
return (
target.type() === 'page' ||
(target.type() === 'other' &&
@ -812,7 +812,7 @@ export class BrowserContext extends EventEmitter {
))
);
})
.map((target) => {
.map(target => {
return target.page();
})
);
@ -847,7 +847,7 @@ export class BrowserContext extends EventEmitter {
origin: string,
permissions: Permission[]
): Promise<void> {
const protocolPermissions = permissions.map((permission) => {
const protocolPermissions = permissions.map(permission => {
const protocolPermission =
WEB_PERMISSION_TO_PROTOCOL_PERMISSION.get(permission);
if (!protocolPermission) {

View File

@ -33,7 +33,7 @@ export class BrowserWebSocketTransport implements ConnectionTransport {
constructor(ws: WebSocket) {
this.#ws = ws;
this.#ws.addEventListener('message', (event) => {
this.#ws.addEventListener('message', event => {
if (this.onmessage) {
this.onmessage.call(null, event.data);
}

View File

@ -120,9 +120,7 @@ export class Connection extends EventEmitter {
*/
_rawSend(message: Record<string, unknown>): number {
const id = ++this.#lastId;
const stringifiedMessage = JSON.stringify(
Object.assign({}, message, { id })
);
const stringifiedMessage = JSON.stringify(Object.assign({}, message, {id}));
debugProtocolSend(stringifiedMessage);
this.#transport.send(stringifiedMessage);
return id;
@ -130,7 +128,7 @@ export class Connection extends EventEmitter {
async #onMessage(message: string): Promise<void> {
if (this.#delay) {
await new Promise((f) => {
await new Promise(f => {
return setTimeout(f, this.#delay);
});
}

View File

@ -15,11 +15,7 @@
*/
import {assert} from './assert.js';
import {
addEventListener,
debugError,
PuppeteerEventListener,
} from './util.js';
import {addEventListener, debugError, PuppeteerEventListener} from './util.js';
import {Protocol} from 'devtools-protocol';
import {CDPSession} from './Connection.js';
@ -480,7 +476,7 @@ function convertToDisjointRanges(
}
}
// Filter out empty ranges.
return results.filter((range) => {
return results.filter(range => {
return range.end - range.start > 1;
});
}

View File

@ -37,10 +37,7 @@ import {
} from './util.js';
import {MouseButton} from './Input.js';
import {ElementHandle, JSHandle} from './JSHandle.js';
import {
LifecycleWatcher,
PuppeteerLifeCycleEvent,
} from './LifecycleWatcher.js';
import {LifecycleWatcher, PuppeteerLifeCycleEvent} from './LifecycleWatcher.js';
import {_getQueryHandlerAndSelector} from './QueryHandler.js';
import {TimeoutSettings} from './TimeoutSettings.js';
@ -149,7 +146,7 @@ export class DOMWorld {
}
} else {
this.#documentPromise = null;
this.#contextPromise = new Promise((fulfill) => {
this.#contextPromise = new Promise(fulfill => {
this.#contextResolveCallback = fulfill;
});
}
@ -221,7 +218,7 @@ export class DOMWorld {
if (this.#documentPromise) {
return this.#documentPromise;
}
this.#documentPromise = this.executionContext().then(async (context) => {
this.#documentPromise = this.executionContext().then(async context => {
const document = await context.evaluateHandle('document');
const element = document.asElement();
if (element === null) {
@ -301,7 +298,7 @@ export class DOMWorld {
} = options;
// We rely upon the fact that document.open() will reset frame lifecycle with "init"
// lifecycle event. @see https://crrev.com/608658
await this.evaluate<(x: string) => void>((html) => {
await this.evaluate<(x: string) => void>(html => {
document.open();
document.write(html);
document.close();
@ -445,7 +442,7 @@ export class DOMWorld {
script.id = id;
}
let error = null;
script.onerror = (e) => {
script.onerror = e => {
return (error = e);
};
document.head.appendChild(script);
@ -992,7 +989,7 @@ export class WaitTask {
if (
!error &&
(await this.#domWorld
.evaluate((s) => {
.evaluate(s => {
return !s;
}, success)
.catch(() => {
@ -1085,7 +1082,7 @@ async function waitForPredicatePageFunction(
}
let fulfill = (_?: unknown) => {};
const result = new Promise((x) => {
const result = new Promise(x => {
return (fulfill = x);
});
const observer = new MutationObserver(async () => {
@ -1114,7 +1111,7 @@ async function waitForPredicatePageFunction(
async function pollRaf(): Promise<unknown> {
let fulfill = (_?: unknown): void => {};
const result = new Promise((x) => {
const result = new Promise(x => {
return (fulfill = x);
});
await onRaf();
@ -1138,7 +1135,7 @@ async function waitForPredicatePageFunction(
async function pollInterval(pollInterval: number): Promise<unknown> {
let fulfill = (_?: unknown): void => {};
const result = new Promise((x) => {
const result = new Promise(x => {
return (fulfill = x);
});
await onTimeout();

View File

@ -110,7 +110,7 @@ export class EventEmitter implements CommonEventEmitter {
* @returns `this` to enable you to chain method calls.
*/
once(event: EventType, handler: Handler): EventEmitter {
const onceHandler: Handler = (eventData) => {
const onceHandler: Handler = eventData => {
handler(eventData);
this.off(event, onceHandler);
};

View File

@ -20,11 +20,7 @@ import { CDPSession } from './Connection.js';
import {DOMWorld} from './DOMWorld.js';
import {EvaluateHandleFn, SerializableOrJSHandle} from './EvalTypes.js';
import {Frame} from './FrameManager.js';
import {
getExceptionMessage,
isString,
valueFromRemoteObject,
} from './util.js';
import {getExceptionMessage, isString, valueFromRemoteObject} from './util.js';
import {ElementHandle, JSHandle, _createJSHandle} from './JSHandle.js';
/**

View File

@ -31,10 +31,7 @@ import { EVALUATION_SCRIPT_URL, ExecutionContext } from './ExecutionContext.js';
import {HTTPResponse} from './HTTPResponse.js';
import {MouseButton} from './Input.js';
import {ElementHandle, JSHandle} from './JSHandle.js';
import {
LifecycleWatcher,
PuppeteerLifeCycleEvent,
} from './LifecycleWatcher.js';
import {LifecycleWatcher, PuppeteerLifeCycleEvent} from './LifecycleWatcher.js';
import {NetworkManager} from './NetworkManager.js';
import {Page} from './Page.js';
import {TimeoutSettings} from './TimeoutSettings.js';
@ -104,13 +101,13 @@ export class FrameManager extends EventEmitter {
}
private setupEventListeners(session: CDPSession) {
session.on('Page.frameAttached', (event) => {
session.on('Page.frameAttached', event => {
this.#onFrameAttached(session, event.frameId, event.parentFrameId);
});
session.on('Page.frameNavigated', (event) => {
session.on('Page.frameNavigated', event => {
this.#onFrameNavigated(event.frame);
});
session.on('Page.navigatedWithinDocument', (event) => {
session.on('Page.navigatedWithinDocument', event => {
this.#onFrameNavigatedWithinDocument(event.frameId, event.url);
});
session.on(
@ -122,28 +119,28 @@ export class FrameManager extends EventEmitter {
);
}
);
session.on('Page.frameStartedLoading', (event) => {
session.on('Page.frameStartedLoading', event => {
this.#onFrameStartedLoading(event.frameId);
});
session.on('Page.frameStoppedLoading', (event) => {
session.on('Page.frameStoppedLoading', event => {
this.#onFrameStoppedLoading(event.frameId);
});
session.on('Runtime.executionContextCreated', (event) => {
session.on('Runtime.executionContextCreated', event => {
this.#onExecutionContextCreated(event.context, session);
});
session.on('Runtime.executionContextDestroyed', (event) => {
session.on('Runtime.executionContextDestroyed', event => {
this.#onExecutionContextDestroyed(event.executionContextId, session);
});
session.on('Runtime.executionContextsCleared', () => {
this.#onExecutionContextsCleared(session);
});
session.on('Page.lifecycleEvent', (event) => {
session.on('Page.lifecycleEvent', event => {
this.#onLifecycleEvent(event);
});
session.on('Target.attachedToTarget', async (event) => {
session.on('Target.attachedToTarget', async event => {
this.#onAttachedToTarget(event);
});
session.on('Target.detachedFromTarget', async (event) => {
session.on('Target.detachedFromTarget', async event => {
this.#onDetachedFromTarget(event);
});
}
@ -443,10 +440,10 @@ export class FrameManager extends EventEmitter {
// Frames might be removed before we send this.
await Promise.all(
this.frames()
.filter((frame) => {
.filter(frame => {
return frame._client() === session;
})
.map((frame) => {
.map(frame => {
return session
.send('Page.createIsolatedWorld', {
frameId: frame._id,
@ -1283,7 +1280,7 @@ export class Frame {
return this.waitForSelector(string, options);
}
if (isNumber(selectorOrFunctionOrTimeout)) {
return new Promise((fulfill) => {
return new Promise(fulfill => {
return setTimeout(fulfill, selectorOrFunctionOrTimeout);
});
}
@ -1320,7 +1317,7 @@ export class Frame {
* @param milliseconds - the number of milliseconds to wait.
*/
waitForTimeout(milliseconds: number): Promise<void> {
return new Promise((resolve) => {
return new Promise(resolve => {
setTimeout(resolve, milliseconds);
});
}

View File

@ -492,7 +492,7 @@ export class HTTPRequest {
postData: postDataBinaryBase64,
headers: headers ? headersArray(headers) : undefined,
})
.catch((error) => {
.catch(error => {
this.#interceptionHandled = false;
return handleError(error);
});
@ -575,7 +575,7 @@ export class HTTPRequest {
const value = response.headers[header];
responseHeaders[header.toLowerCase()] = Array.isArray(value)
? value.map((item) => {
? value.map(item => {
return String(item);
})
: String(value);
@ -604,7 +604,7 @@ export class HTTPRequest {
responseHeaders: headersArray(responseHeaders),
body: responseBody ? responseBody.toString('base64') : undefined,
})
.catch((error) => {
.catch(error => {
this.#interceptionHandled = false;
return handleError(error);
});
@ -740,7 +740,7 @@ function headersArray(
const values = Array.isArray(value) ? value : [value];
result.push(
...values.map((value) => {
...values.map(value => {
return {name, value: value + ''};
})
);

View File

@ -71,7 +71,7 @@ export class HTTPResponse {
this.#client = client;
this.#request = request;
this.#bodyLoadedPromise = new Promise((fulfill) => {
this.#bodyLoadedPromise = new Promise(fulfill => {
this.#bodyLoadedPromiseFulfill = fulfill;
});
@ -195,7 +195,7 @@ export class HTTPResponse {
*/
buffer(): Promise<Buffer> {
if (!this.#contentPromise) {
this.#contentPromise = this.#bodyLoadedPromise.then(async (error) => {
this.#contentPromise = this.#bodyLoadedPromise.then(async error => {
if (error) {
throw error;
}

View File

@ -16,11 +16,7 @@
import {assert} from './assert.js';
import {CDPSession} from './Connection.js';
import {
_keyDefinitions,
KeyDefinition,
KeyInput,
} from './USKeyboardLayout.js';
import {_keyDefinitions, KeyDefinition, KeyInput} from './USKeyboardLayout.js';
import {Protocol} from 'devtools-protocol';
import {Point} from './JSHandle.js';
@ -277,7 +273,7 @@ export class Keyboard {
await this.press(char, {delay});
} else {
if (delay) {
await new Promise((f) => {
await new Promise(f => {
return setTimeout(f, delay);
});
}
@ -313,7 +309,7 @@ export class Keyboard {
const {delay = null} = options;
await this.down(key, options);
if (delay) {
await new Promise((f) => {
await new Promise(f => {
return setTimeout(f, options.delay);
});
}
@ -457,7 +453,7 @@ export class Mouse {
if (delay !== null) {
await this.move(x, y);
await this.down(options);
await new Promise((f) => {
await new Promise(f => {
return setTimeout(f, delay);
});
await this.up(options);
@ -540,8 +536,8 @@ export class Mouse {
* @param target - point to drag to
*/
async drag(start: Point, target: Point): Promise<Protocol.Input.DragData> {
const promise = new Promise<Protocol.Input.DragData>((resolve) => {
this.#client.once('Input.dragIntercepted', (event) => {
const promise = new Promise<Protocol.Input.DragData>(resolve => {
this.#client.once('Input.dragIntercepted', event => {
return resolve(event.data);
});
});
@ -614,7 +610,7 @@ export class Mouse {
await this.dragEnter(target, data);
await this.dragOver(target, data);
if (delay) {
await new Promise((resolve) => {
await new Promise(resolve => {
return setTimeout(resolve, delay);
});
}

View File

@ -91,7 +91,7 @@ const applyOffsetsToQuad = (
offsetX: number,
offsetY: number
) => {
return quad.map((part) => {
return quad.map(part => {
return {x: part.x + offsetX, y: part.y + offsetY};
});
};
@ -561,8 +561,8 @@ export class ElementHandle<
});
return false;
}
const visibleRatio = await new Promise((resolve) => {
const observer = new IntersectionObserver((entries) => {
const visibleRatio = await new Promise(resolve => {
const observer = new IntersectionObserver(entries => {
resolve(entries[0]!.intersectionRatio);
observer.disconnect();
});
@ -600,9 +600,7 @@ export class ElementHandle<
currentFrame = parent;
continue;
}
const { backendNodeId } = await parent
._client()
.send('DOM.getFrameOwner', {
const {backendNodeId} = await parent._client().send('DOM.getFrameOwner', {
frameId: currentFrame._id,
});
const result = await parent._client().send('DOM.getBoxModel', {
@ -641,16 +639,16 @@ export class ElementHandle<
layoutMetrics.cssLayoutViewport || layoutMetrics.layoutViewport;
const {offsetX, offsetY} = await this.#getOOPIFOffsets(this.#frame);
const quads = result.quads
.map((quad) => {
.map(quad => {
return this.#fromProtocolQuad(quad);
})
.map((quad) => {
.map(quad => {
return applyOffsetsToQuad(quad, offsetX, offsetY);
})
.map((quad) => {
.map(quad => {
return this.#intersectQuadWithViewport(quad, clientWidth, clientHeight);
})
.filter((quad) => {
.filter(quad => {
return computeQuadArea(quad) > 1;
});
if (!quads.length) {
@ -696,7 +694,7 @@ export class ElementHandle<
const params: Protocol.DOM.GetBoxModelRequest = {
objectId: this._remoteObject.objectId,
};
return this._client.send('DOM.getBoxModel', params).catch((error) => {
return this._client.send('DOM.getBoxModel', params).catch(error => {
return debugError(error);
});
}
@ -715,7 +713,7 @@ export class ElementHandle<
width: number,
height: number
): Point[] {
return quad.map((point) => {
return quad.map(point => {
return {
x: Math.min(Math.max(point.x, 0), width),
y: Math.min(Math.max(point.y, 0), height),
@ -874,7 +872,7 @@ export class ElementHandle<
*/
async uploadFile(...filePaths: string[]): Promise<void> {
const isMultiple = await this.evaluate<(element: Element) => boolean>(
(element) => {
element => {
if (!(element instanceof HTMLInputElement)) {
throw new Error('uploadFile can only be called on an input element.');
}
@ -898,7 +896,7 @@ export class ElementHandle<
}
throw error;
}
const files = filePaths.map((filePath) => {
const files = filePaths.map(filePath => {
if (path.win32.isAbsolute(filePath) || path.posix.isAbsolute(filePath)) {
return filePath;
} else {
@ -914,7 +912,7 @@ export class ElementHandle<
so the solution is to eval the element value to a new FileList directly.
*/
if (files.length === 0) {
await (this as ElementHandle<HTMLInputElement>).evaluate((element) => {
await (this as ElementHandle<HTMLInputElement>).evaluate(element => {
element.files = new DataTransfer().files;
// Dispatch events for this case because it should behave akin to a user action.
@ -945,7 +943,7 @@ export class ElementHandle<
* Calls {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus | focus} on the element.
*/
async focus(): Promise<void> {
await (this as ElementHandle<HTMLElement>).evaluate((element) => {
await (this as ElementHandle<HTMLElement>).evaluate(element => {
return element.focus();
});
}
@ -1302,8 +1300,8 @@ export class ElementHandle<
}): Promise<boolean> {
const {threshold = 0} = options || {};
return await this.evaluate(async (element: Element, threshold: number) => {
const visibleRatio = await new Promise<number>((resolve) => {
const observer = new IntersectionObserver((entries) => {
const visibleRatio = await new Promise<number>(resolve => {
const observer = new IntersectionObserver(entries => {
resolve(entries[0]!.intersectionRatio);
observer.disconnect();
});

View File

@ -72,24 +72,24 @@ export class LifecycleWatcher {
#eventListeners: PuppeteerEventListener[];
#sameDocumentNavigationCompleteCallback: (x?: Error) => void = noop;
#sameDocumentNavigationPromise = new Promise<Error | undefined>((fulfill) => {
#sameDocumentNavigationPromise = new Promise<Error | undefined>(fulfill => {
this.#sameDocumentNavigationCompleteCallback = fulfill;
});
#lifecycleCallback: () => void = noop;
#lifecyclePromise: Promise<void> = new Promise((fulfill) => {
#lifecyclePromise: Promise<void> = new Promise(fulfill => {
this.#lifecycleCallback = fulfill;
});
#newDocumentNavigationCompleteCallback: (x?: Error) => void = noop;
#newDocumentNavigationPromise: Promise<Error | undefined> = new Promise(
(fulfill) => {
fulfill => {
this.#newDocumentNavigationCompleteCallback = fulfill;
}
);
#terminationCallback: (x?: Error) => void = noop;
#terminationPromise: Promise<Error | undefined> = new Promise((fulfill) => {
#terminationPromise: Promise<Error | undefined> = new Promise(fulfill => {
this.#terminationCallback = fulfill;
});
@ -111,7 +111,7 @@ export class LifecycleWatcher {
} else if (typeof waitUntil === 'string') {
waitUntil = [waitUntil];
}
this.#expectedLifecycle = waitUntil.map((value) => {
this.#expectedLifecycle = waitUntil.map(value => {
const protocolEvent = puppeteerToProtocolLifecycle.get(value);
assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);
return protocolEvent as ProtocolLifeCycleEvent;
@ -214,7 +214,7 @@ export class LifecycleWatcher {
}
const errorMessage =
'Navigation timeout of ' + this.#timeout + ' ms exceeded';
await new Promise((fulfill) => {
await new Promise(fulfill => {
return (this.#maximumTimer = setTimeout(fulfill, this.#timeout));
});
return new TimeoutError(errorMessage);

View File

@ -19,11 +19,7 @@ import type { Readable } from 'stream';
import {Accessibility} from './Accessibility.js';
import {assert, assertNever} from './assert.js';
import {Browser, BrowserContext} from './Browser.js';
import {
CDPSession,
CDPSessionEmittedEvents,
Connection,
} from './Connection.js';
import {CDPSession, CDPSessionEmittedEvents, Connection} from './Connection.js';
import {ConsoleMessage, ConsoleMessageType} from './ConsoleMessage.js';
import {Coverage} from './Coverage.js';
import {Dialog} from './Dialog.js';
@ -71,11 +67,7 @@ import {
NetworkConditions,
NetworkManagerEmittedEvents,
} from './NetworkManager.js';
import {
LowerCasePaperFormat,
PDFOptions,
_paperFormats,
} from './PDFOptions.js';
import {LowerCasePaperFormat, PDFOptions, _paperFormats} from './PDFOptions.js';
import {Viewport} from './PuppeteerViewport.js';
import {Target} from './Target.js';
import {TaskQueue} from './TaskQueue.js';
@ -545,7 +537,7 @@ export class Page extends EventEmitter {
}
}
);
client.on('Target.detachedFromTarget', (event) => {
client.on('Target.detachedFromTarget', event => {
const worker = this.#workers.get(event.sessionId);
if (!worker) {
return;
@ -554,33 +546,33 @@ export class Page extends EventEmitter {
this.emit(PageEmittedEvents.WorkerDestroyed, worker);
});
this.#frameManager.on(FrameManagerEmittedEvents.FrameAttached, (event) => {
this.#frameManager.on(FrameManagerEmittedEvents.FrameAttached, event => {
return this.emit(PageEmittedEvents.FrameAttached, event);
});
this.#frameManager.on(FrameManagerEmittedEvents.FrameDetached, (event) => {
this.#frameManager.on(FrameManagerEmittedEvents.FrameDetached, event => {
return this.emit(PageEmittedEvents.FrameDetached, event);
});
this.#frameManager.on(FrameManagerEmittedEvents.FrameNavigated, (event) => {
this.#frameManager.on(FrameManagerEmittedEvents.FrameNavigated, event => {
return this.emit(PageEmittedEvents.FrameNavigated, event);
});
const networkManager = this.#frameManager.networkManager();
networkManager.on(NetworkManagerEmittedEvents.Request, (event) => {
networkManager.on(NetworkManagerEmittedEvents.Request, event => {
return this.emit(PageEmittedEvents.Request, event);
});
networkManager.on(
NetworkManagerEmittedEvents.RequestServedFromCache,
(event) => {
event => {
return this.emit(PageEmittedEvents.RequestServedFromCache, event);
}
);
networkManager.on(NetworkManagerEmittedEvents.Response, (event) => {
networkManager.on(NetworkManagerEmittedEvents.Response, event => {
return this.emit(PageEmittedEvents.Response, event);
});
networkManager.on(NetworkManagerEmittedEvents.RequestFailed, (event) => {
networkManager.on(NetworkManagerEmittedEvents.RequestFailed, event => {
return this.emit(PageEmittedEvents.RequestFailed, event);
});
networkManager.on(NetworkManagerEmittedEvents.RequestFinished, (event) => {
networkManager.on(NetworkManagerEmittedEvents.RequestFinished, event => {
return this.emit(PageEmittedEvents.RequestFinished, event);
});
this.#fileChooserInterceptors = new Set();
@ -591,28 +583,28 @@ export class Page extends EventEmitter {
client.on('Page.loadEventFired', () => {
return this.emit(PageEmittedEvents.Load);
});
client.on('Runtime.consoleAPICalled', (event) => {
client.on('Runtime.consoleAPICalled', event => {
return this.#onConsoleAPI(event);
});
client.on('Runtime.bindingCalled', (event) => {
client.on('Runtime.bindingCalled', event => {
return this.#onBindingCalled(event);
});
client.on('Page.javascriptDialogOpening', (event) => {
client.on('Page.javascriptDialogOpening', event => {
return this.#onDialog(event);
});
client.on('Runtime.exceptionThrown', (exception) => {
client.on('Runtime.exceptionThrown', exception => {
return this.#handleException(exception.exceptionDetails);
});
client.on('Inspector.targetCrashed', () => {
return this.#onTargetCrashed();
});
client.on('Performance.metrics', (event) => {
client.on('Performance.metrics', event => {
return this.#emitMetrics(event);
});
client.on('Log.entryAdded', (event) => {
client.on('Log.entryAdded', event => {
return this.#onLogEntryAdded(event);
});
client.on('Page.fileChooserOpened', (event) => {
client.on('Page.fileChooserOpened', event => {
return this.#onFileChooser(event);
});
this.#target._isClosedPromise.then(() => {
@ -745,7 +737,7 @@ export class Page extends EventEmitter {
const {timeout = this.#timeoutSettings.timeout()} = options;
let callback!: (value: FileChooser | PromiseLike<FileChooser>) => void;
const promise = new Promise<FileChooser>((x) => {
const promise = new Promise<FileChooser>(x => {
return (callback = x);
});
this.#fileChooserInterceptors.add(callback);
@ -753,7 +745,7 @@ export class Page extends EventEmitter {
promise,
'waiting for file chooser',
timeout
).catch((error) => {
).catch(error => {
this.#fileChooserInterceptors.delete(callback);
throw error;
});
@ -828,7 +820,7 @@ export class Page extends EventEmitter {
#onLogEntryAdded(event: Protocol.Log.EntryAddedEvent): void {
const {level, text, args, source, url, lineNumber} = event.entry;
if (args) {
args.map((arg) => {
args.map(arg => {
return releaseObject(this.#client, arg);
});
}
@ -1337,7 +1329,7 @@ export class Page extends EventEmitter {
async setCookie(...cookies: Protocol.Network.CookieParam[]): Promise<void> {
const pageURL = this.url();
const startsWithHTTP = pageURL.startsWith('http');
const items = cookies.map((cookie) => {
const items = cookies.map(cookie => {
const item = Object.assign({}, cookie);
if (!item.url && startsWithHTTP) {
item.url = pageURL;
@ -1477,7 +1469,7 @@ export class Page extends EventEmitter {
source: expression,
});
await Promise.all(
this.frames().map((frame) => {
this.frames().map(frame => {
return frame.evaluate(expression).catch(debugError);
})
);
@ -1609,7 +1601,7 @@ export class Page extends EventEmitter {
event.executionContextId,
this.#client
);
const values = event.args.map((arg) => {
const values = event.args.map(arg => {
return _createJSHandle(context, arg);
});
this.#addConsoleMessage(event.type, values, event.stackTrace);
@ -1662,7 +1654,7 @@ export class Page extends EventEmitter {
stackTrace?: Protocol.Runtime.StackTrace
): void {
if (!this.listenerCount(PageEmittedEvents.Console)) {
args.forEach((arg) => {
args.forEach(arg => {
return arg.dispose();
});
return;
@ -1910,7 +1902,7 @@ export class Page extends EventEmitter {
#sessionClosePromise(): Promise<Error> {
if (!this.#disconnectPromise) {
this.#disconnectPromise = new Promise((fulfill) => {
this.#disconnectPromise = new Promise(fulfill => {
return this.#client.once(CDPSessionEmittedEvents.Disconnected, () => {
return fulfill(new Error('Target closed'));
});
@ -1952,7 +1944,7 @@ export class Page extends EventEmitter {
return waitForEvent(
this.#frameManager.networkManager(),
NetworkManagerEmittedEvents.Request,
(request) => {
request => {
if (isString(urlOrPredicate)) {
return urlOrPredicate === request.url();
}
@ -2001,7 +1993,7 @@ export class Page extends EventEmitter {
return waitForEvent(
this.#frameManager.networkManager(),
NetworkManagerEmittedEvents.Response,
async (response) => {
async response => {
if (isString(urlOrPredicate)) {
return urlOrPredicate === response.url();
}
@ -2022,13 +2014,12 @@ export class Page extends EventEmitter {
async waitForNetworkIdle(
options: {idleTime?: number; timeout?: number} = {}
): Promise<void> {
const { idleTime = 500, timeout = this.#timeoutSettings.timeout() } =
options;
const {idleTime = 500, timeout = this.#timeoutSettings.timeout()} = options;
const networkManager = this.#frameManager.networkManager();
let idleResolveCallback: () => void;
const idlePromise = new Promise<void>((resolve) => {
const idlePromise = new Promise<void>(resolve => {
idleResolveCallback = resolve;
});
@ -2081,11 +2072,11 @@ export class Page extends EventEmitter {
...eventPromises,
this.#sessionClosePromise(),
]).then(
(r) => {
r => {
cleanup();
return r;
},
(error) => {
error => {
cleanup();
throw error;
}
@ -2145,7 +2136,7 @@ export class Page extends EventEmitter {
timeout,
this.#sessionClosePromise()
),
...this.frames().map(async (frame) => {
...this.frames().map(async frame => {
if (await predicate(frame)) {
return frame;
}

View File

@ -25,10 +25,7 @@ import {
CustomQueryHandler,
} from './QueryHandler.js';
import {Product} from './Product.js';
import {
_connectToBrowser,
BrowserConnectOptions,
} from './BrowserConnector.js';
import {_connectToBrowser, BrowserConnectOptions} from './BrowserConnector.js';
import {
PredefinedNetworkConditions,
networkConditions,

View File

@ -211,7 +211,7 @@ export function _unregisterCustomQueryHandler(name: string): void {
* @internal
*/
export function _customQueryHandlerNames(): string[] {
return [...queryHandlers.keys()].filter((name) => {
return [...queryHandlers.keys()].filter(name => {
return !builtInHandlers.has(name);
});
}

View File

@ -84,9 +84,9 @@ export class Target {
this.#defaultViewport = defaultViewport ?? undefined;
this.#screenshotTaskQueue = screenshotTaskQueue;
this._isPageTargetCallback = isPageTargetCallback;
this._initializedPromise = new Promise<boolean>((fulfill) => {
this._initializedPromise = new Promise<boolean>(fulfill => {
return (this._initializedCallback = fulfill);
}).then(async (success) => {
}).then(async success => {
if (!success) {
return false;
}
@ -102,7 +102,7 @@ export class Target {
openerPage.emit(PageEmittedEvents.Popup, popupPage);
return true;
});
this._isClosedPromise = new Promise<void>((fulfill) => {
this._isClosedPromise = new Promise<void>(fulfill => {
return (this._closedCallback = fulfill);
});
this._isInitialized =
@ -132,7 +132,7 @@ export class Target {
*/
async page(): Promise<Page | null> {
if (this._isPageTargetCallback(this.#targetInfo) && !this.#pagePromise) {
this.#pagePromise = this.#sessionFactory().then((client) => {
this.#pagePromise = this.#sessionFactory().then(client => {
return Page._create(
client,
this,
@ -157,7 +157,7 @@ export class Target {
}
if (!this.#workerPromise) {
// TODO(einbinder): Make workers send their console logs.
this.#workerPromise = this.#sessionFactory().then((client) => {
this.#workerPromise = this.#sessionFactory().then(client => {
return new WebWorker(
client,
this.#targetInfo.url,

View File

@ -83,24 +83,20 @@ export class Tracing {
'disabled-by-default-devtools.timeline.stack',
'disabled-by-default-v8.cpu_profiler',
];
const {
path,
screenshots = false,
categories = defaultCategories,
} = options;
const {path, screenshots = false, categories = defaultCategories} = options;
if (screenshots) {
categories.push('disabled-by-default-devtools.screenshot');
}
const excludedCategories = categories
.filter((cat) => {
.filter(cat => {
return cat.startsWith('-');
})
.map((cat) => {
.map(cat => {
return cat.slice(1);
});
const includedCategories = categories.filter((cat) => {
const includedCategories = categories.filter(cat => {
return !cat.startsWith('-');
});
@ -126,7 +122,7 @@ export class Tracing {
resolve = x;
reject = y;
});
this.#client.once('Tracing.tracingComplete', async (event) => {
this.#client.once('Tracing.tracingComplete', async event => {
try {
const readable = await getReadableFromProtocolStream(
this.#client,

View File

@ -79,14 +79,14 @@ export class WebWorker extends EventEmitter {
super();
this.#client = client;
this.#url = url;
this.#executionContextPromise = new Promise<ExecutionContext>((x) => {
this.#executionContextPromise = new Promise<ExecutionContext>(x => {
return (this.#executionContextCallback = x);
});
let jsHandleFactory: JSHandleFactory;
this.#client.once('Runtime.executionContextCreated', async (event) => {
this.#client.once('Runtime.executionContextCreated', async event => {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
jsHandleFactory = (remoteObject) => {
jsHandleFactory = remoteObject => {
return new JSHandle(executionContext, client, remoteObject);
};
const executionContext = new ExecutionContext(client, event.context);
@ -95,14 +95,14 @@ export class WebWorker extends EventEmitter {
// This might fail if the target is closed before we receive all execution contexts.
this.#client.send('Runtime.enable').catch(debugError);
this.#client.on('Runtime.consoleAPICalled', (event) => {
this.#client.on('Runtime.consoleAPICalled', event => {
return consoleAPICalled(
event.type,
event.args.map(jsHandleFactory),
event.stackTrace
);
});
this.#client.on('Runtime.exceptionThrown', (exception) => {
this.#client.on('Runtime.exceptionThrown', exception => {
return exceptionThrown(exception.exceptionDetails);
});
}

View File

@ -85,7 +85,7 @@ export async function releaseObject(
}
await client
.send('Runtime.releaseObject', {objectId: remoteObject.objectId})
.catch((error) => {
.catch(error => {
// Exceptions might happen in case of a page been navigated or closed.
// Swallow these since they are harmless and we don't leak anything in this case.
debugError(error);
@ -142,7 +142,7 @@ export async function waitForEvent<T>(
resolveCallback = resolve;
rejectCallback = reject;
});
const listener = addEventListener(emitter, eventName, async (event) => {
const listener = addEventListener(emitter, eventName, async event => {
if (!(await predicate(event))) {
return;
}
@ -160,11 +160,11 @@ export async function waitForEvent<T>(
clearTimeout(eventTimeout);
}
const result = await Promise.race([promise, abortPromise]).then(
(r) => {
r => {
cleanup();
return r;
},
(error) => {
error => {
cleanup();
throw error;
}

View File

@ -142,8 +142,8 @@ const unlinkAsync = promisify(fs.unlink.bind(fs));
const chmodAsync = promisify(fs.chmod.bind(fs));
function existsAsync(filePath: string): Promise<boolean> {
return new Promise((resolve) => {
fs.access(filePath, (err) => {
return new Promise(resolve => {
fs.access(filePath, err => {
return resolve(!err);
});
});
@ -288,16 +288,16 @@ export class BrowserFetcher {
this.#downloadHost,
revision
);
return new Promise((resolve) => {
return new Promise(resolve => {
const request = httpRequest(
url,
'HEAD',
(response) => {
response => {
resolve(response.statusCode === 200);
},
false
);
request.on('error', (error) => {
request.on('error', error => {
console.error(error);
resolve(false);
});
@ -367,7 +367,7 @@ export class BrowserFetcher {
}
const fileNames = await readdirAsync(this.#downloadsFolder);
return fileNames
.map((fileName) => {
.map(fileName => {
return parseFolderPath(this.#product, fileName);
})
.filter(
@ -377,7 +377,7 @@ export class BrowserFetcher {
return (entry && entry.platform === this.#platform) ?? false;
}
)
.map((entry) => {
.map(entry => {
return entry.revision;
});
}
@ -395,7 +395,7 @@ export class BrowserFetcher {
await existsAsync(folderPath),
`Failed to remove: revision ${revision} is not downloaded`
);
await new Promise((fulfill) => {
await new Promise(fulfill => {
return removeRecursive(folderPath, fulfill);
});
}
@ -516,7 +516,7 @@ function _downloadFile(
let downloadedBytes = 0;
let totalBytes = 0;
const request = httpRequest(url, 'GET', (response) => {
const request = httpRequest(url, 'GET', response => {
if (response.statusCode !== 200) {
const error = new Error(
`Download failed: server returned code ${response.statusCode}. URL: ${url}`
@ -530,7 +530,7 @@ function _downloadFile(
file.on('finish', () => {
return fulfill();
});
file.on('error', (error) => {
file.on('error', error => {
return reject(error);
});
response.pipe(file);
@ -539,7 +539,7 @@ function _downloadFile(
response.on('data', onData);
}
});
request.on('error', (error) => {
request.on('error', error => {
return reject(error);
});
return promise;
@ -596,8 +596,8 @@ function _installDMG(dmgPath: string, folderPath: string): Promise<void> {
}
mountPath = volumes[0]!;
readdirAsync(mountPath)
.then((fileNames) => {
const appName = fileNames.find((item) => {
.then(fileNames => {
const appName = fileNames.find(item => {
return typeof item === 'string' && item.endsWith('.app');
});
if (!appName) {
@ -605,7 +605,7 @@ function _installDMG(dmgPath: string, folderPath: string): Promise<void> {
}
const copyPath = path.join(mountPath!, appName);
debugFetcher(`Copying ${copyPath} to ${folderPath}`);
childProcess.exec(`cp -R "${copyPath}" "${folderPath}"`, (err) => {
childProcess.exec(`cp -R "${copyPath}" "${folderPath}"`, err => {
if (err) {
reject(err);
} else {
@ -616,7 +616,7 @@ function _installDMG(dmgPath: string, folderPath: string): Promise<void> {
.catch(reject);
});
})
.catch((error) => {
.catch(error => {
console.error(error);
})
.finally((): void => {
@ -625,7 +625,7 @@ function _installDMG(dmgPath: string, folderPath: string): Promise<void> {
}
const unmountCommand = `hdiutil detach "${mountPath}" -quiet`;
debugFetcher(`Unmounting ${mountPath}`);
childProcess.exec(unmountCommand, (err) => {
childProcess.exec(unmountCommand, err => {
if (err) {
console.error(`Error unmounting dmg: ${err}`);
}

View File

@ -181,7 +181,7 @@ export class BrowserRunner {
this.kill();
} else if (this.connection) {
// Attempt to close the browser gracefully
this.connection.send('Browser.close').catch((error) => {
this.connection.send('Browser.close').catch(error => {
debugError(error);
this.kill();
});
@ -200,7 +200,7 @@ export class BrowserRunner {
const proc = this.proc;
try {
if (process.platform === 'win32') {
childProcess.exec(`taskkill /pid ${this.proc.pid} /T /F`, (error) => {
childProcess.exec(`taskkill /pid ${this.proc.pid} /T /F`, error => {
if (error) {
// taskkill can fail to kill the process e.g. due to missing permissions.
// Let's kill the process via Node API. This delays killing of all child
@ -292,7 +292,7 @@ function waitForWSEndpoint(
addEventListener(browserProcess, 'exit', () => {
return onClose();
}),
addEventListener(browserProcess, 'error', (error) => {
addEventListener(browserProcess, 'error', error => {
return onClose(error);
}),
];

View File

@ -102,7 +102,7 @@ class ChromeLauncher implements ProductLauncher {
chromeArguments.push(...this.defaultArgs(options));
} else if (Array.isArray(ignoreDefaultArgs)) {
chromeArguments.push(
...this.defaultArgs(options).filter((arg) => {
...this.defaultArgs(options).filter(arg => {
return !ignoreDefaultArgs.includes(arg);
})
);
@ -111,7 +111,7 @@ class ChromeLauncher implements ProductLauncher {
}
if (
!chromeArguments.some((argument) => {
!chromeArguments.some(argument => {
return argument.startsWith('--remote-debugging-');
})
) {
@ -130,7 +130,7 @@ class ChromeLauncher implements ProductLauncher {
// Check for the user data dir argument, which will always be set even
// with a custom directory specified via the userDataDir option.
let userDataDirIndex = chromeArguments.findIndex((arg) => {
let userDataDirIndex = chromeArguments.findIndex(arg => {
return arg.startsWith('--user-data-dir');
});
if (userDataDirIndex < 0) {
@ -205,7 +205,7 @@ class ChromeLauncher implements ProductLauncher {
if (waitForInitialPage) {
try {
await browser.waitForTarget(
(t) => {
t => {
return t.type() === 'page';
},
{timeout}
@ -272,7 +272,7 @@ class ChromeLauncher implements ProductLauncher {
);
}
if (
args.every((arg) => {
args.every(arg => {
return arg.startsWith('-');
})
) {
@ -348,7 +348,7 @@ class FirefoxLauncher implements ProductLauncher {
firefoxArguments.push(...this.defaultArgs(options));
} else if (Array.isArray(ignoreDefaultArgs)) {
firefoxArguments.push(
...this.defaultArgs(options).filter((arg) => {
...this.defaultArgs(options).filter(arg => {
return !ignoreDefaultArgs.includes(arg);
})
);
@ -357,7 +357,7 @@ class FirefoxLauncher implements ProductLauncher {
}
if (
!firefoxArguments.some((argument) => {
!firefoxArguments.some(argument => {
return argument.startsWith('--remote-debugging-');
})
) {
@ -375,7 +375,7 @@ class FirefoxLauncher implements ProductLauncher {
// Check for the profile argument, which will always be set even
// with a custom directory specified via the userDataDir option.
const profileArgIndex = firefoxArguments.findIndex((arg) => {
const profileArgIndex = firefoxArguments.findIndex(arg => {
return ['-profile', '--profile'].includes(arg);
});
@ -450,7 +450,7 @@ class FirefoxLauncher implements ProductLauncher {
if (waitForInitialPage) {
try {
await browser.waitForTarget(
(t) => {
t => {
return t.type() === 'page';
},
{timeout}
@ -516,7 +516,7 @@ class FirefoxLauncher implements ProductLauncher {
firefoxArguments.push('--devtools');
}
if (
args.every((arg) => {
args.every(arg => {
return arg.startsWith('-');
})
) {

View File

@ -56,7 +56,7 @@ export class NodeWebSocketTransport implements ConnectionTransport {
constructor(ws: NodeWebSocket) {
this.#ws = ws;
this.#ws.addEventListener('message', (event) => {
this.#ws.addEventListener('message', event => {
if (this.onmessage) {
this.onmessage.call(null, event.data);
}

View File

@ -38,7 +38,7 @@ export class PipeTransport implements ConnectionTransport {
) {
this.#pipeWrite = pipeWrite;
this.#eventListeners = [
addEventListener(pipeRead, 'data', (buffer) => {
addEventListener(pipeRead, 'data', buffer => {
return this.#dispatch(buffer);
}),
addEventListener(pipeRead, 'close', () => {

View File

@ -20,10 +20,7 @@ import {
ConnectOptions,
} from '../common/Puppeteer.js';
import {BrowserFetcher, BrowserFetcherOptions} from './BrowserFetcher.js';
import {
LaunchOptions,
BrowserLaunchArgumentOptions,
} from './LaunchOptions.js';
import {LaunchOptions, BrowserLaunchArgumentOptions} from './LaunchOptions.js';
import {BrowserConnectOptions} from '../common/BrowserConnector.js';
import {Browser} from '../common/Browser.js';
import Launcher, {ProductLauncher} from './Launcher.js';

View File

@ -20,9 +20,7 @@ import URL from 'url';
import puppeteer from '../puppeteer.js';
import {PUPPETEER_REVISIONS} from '../revisions.js';
import {PuppeteerNode} from './Puppeteer.js';
import createHttpsProxyAgent, {
HttpsProxyAgentOptions,
} from 'https-proxy-agent';
import createHttpsProxyAgent, {HttpsProxyAgentOptions} from 'https-proxy-agent';
import {getProxyForUrl} from 'proxy-from-env';
const supportedProducts = {
@ -70,7 +68,7 @@ export async function downloadBrowser(): Promise<void> {
} else if (product === 'firefox') {
(puppeteer as PuppeteerNode)._preferredRevision =
PUPPETEER_REVISIONS.firefox;
return getFirefoxNightlyVersion().catch((error) => {
return getFirefoxNightlyVersion().catch(error => {
console.error(error);
process.exit(1);
});
@ -111,10 +109,10 @@ export async function downloadBrowser(): Promise<void> {
logPolitely(
`${supportedProducts[product]} (${revisionInfo.revision}) downloaded to ${revisionInfo.folderPath}`
);
localRevisions = localRevisions.filter((revision) => {
localRevisions = localRevisions.filter(revision => {
return revision !== revisionInfo.revision;
});
const cleanupOldVersions = localRevisions.map((revision) => {
const cleanupOldVersions = localRevisions.map(revision => {
return browserFetcher.remove(revision);
});
Promise.all([...cleanupOldVersions]);
@ -189,11 +187,11 @@ export async function downloadBrowser(): Promise<void> {
`Requesting latest Firefox Nightly version from ${firefoxVersionsUrl}`
);
https
.get(firefoxVersionsUrl, requestOptions, (r) => {
.get(firefoxVersionsUrl, requestOptions, r => {
if (r.statusCode && r.statusCode >= 400) {
return reject(new Error(`Got status code ${r.statusCode}`));
}
r.on('data', (chunk) => {
r.on('data', chunk => {
data += chunk;
});
r.on('end', () => {

View File

@ -48,7 +48,7 @@ describeChromeOnly('Target.createCDPSession', function () {
const client = await page.target().createCDPSession();
await client.send('Network.enable');
const events = [];
client.on('Network.requestWillBeSent', (event) => {
client.on('Network.requestWillBeSent', event => {
return events.push(event);
});
await page.goto(server.EMPTY_PAGE);
@ -99,7 +99,7 @@ describeChromeOnly('Target.createCDPSession', function () {
const {page} = getTestState();
const client = await page.target().createCDPSession();
const error = await theSourceOfTheProblems().catch((error) => {
const error = await theSourceOfTheProblems().catch(error => {
return error;
});
expect(error.stack).toContain('theSourceOfTheProblems');

View File

@ -491,12 +491,10 @@ describeFailsFirefox('Accessibility', function () {
await page.setContent(`<button>My Button</button>`);
const button = (await page.$('button'))!;
await page.$eval('button', (button) => {
await page.$eval('button', button => {
return button.remove();
});
expect(await page.accessibility.snapshot({ root: button })).toEqual(
null
);
expect(await page.accessibility.snapshot({root: button})).toEqual(null);
});
it('should support the interestingOnly option', async () => {
const {page} = getTestState();

View File

@ -174,7 +174,7 @@ describeChromeOnly('AriaQueryHandler', () => {
);
const divs = await page.$$('aria/menu div');
const ids = await Promise.all(
divs.map((n) => {
divs.map(n => {
return n.evaluate((div: Element) => {
return div.id;
});
@ -196,7 +196,7 @@ describeChromeOnly('AriaQueryHandler', () => {
}
`
);
const sum = await page.$$eval('aria/[role="button"]', (buttons) => {
const sum = await page.$$eval('aria/[role="button"]', buttons => {
return buttons.reduce((acc, button) => {
return acc + Number(button.textContent);
}, 0);
@ -348,7 +348,7 @@ describeChromeOnly('AriaQueryHandler', () => {
let waitError!: Error;
const waitPromise = frame!
.waitForSelector('aria/does-not-exist')
.catch((error) => {
.catch(error => {
return (waitError = error);
});
await utils.detachFrame(page, 'frame1');
@ -507,7 +507,7 @@ describeChromeOnly('AriaQueryHandler', () => {
let error!: Error;
await page
.waitForSelector('aria/[role="button"]', {timeout: 10})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -524,7 +524,7 @@ describeChromeOnly('AriaQueryHandler', () => {
let error!: Error;
await page
.waitForSelector('aria/[role="main"]', {hidden: true, timeout: 10})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -566,9 +566,7 @@ describeChromeOnly('AriaQueryHandler', () => {
const {page} = getTestState();
let error!: Error;
await page
.waitForSelector('aria/zombo', { timeout: 10 })
.catch((error_) => {
await page.waitForSelector('aria/zombo', {timeout: 10}).catch(error_ => {
return (error = error_);
});
expect(error!.stack).toContain('waiting for selector `zombo` failed');
@ -626,7 +624,7 @@ describeChromeOnly('AriaQueryHandler', () => {
});
const getIds = async (elements: ElementHandle[]) => {
return Promise.all(
elements.map((element) => {
elements.map(element => {
return element.evaluate((element: Element) => {
return element.id;
});

View File

@ -30,7 +30,7 @@ describe('BrowserContext', function () {
const defaultContext = browser.browserContexts()[0]!;
expect(defaultContext!.isIncognito()).toBe(false);
let error!: Error;
await defaultContext!.close().catch((error_) => {
await defaultContext!.close().catch(error_ => {
return (error = error_);
});
expect(browser.defaultBrowserContext()).toBe(defaultContext);
@ -68,7 +68,7 @@ describe('BrowserContext', function () {
await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([
utils.waitEvent(browser, 'targetcreated'),
page.evaluate<(url: string) => void>((url) => {
page.evaluate<(url: string) => void>(url => {
return window.open(url);
}, server.EMPTY_PAGE),
]);
@ -80,13 +80,13 @@ describe('BrowserContext', function () {
const context = await browser.createIncognitoBrowserContext();
const events: any[] = [];
context.on('targetcreated', (target) => {
context.on('targetcreated', target => {
return events.push('CREATED: ' + target.url());
});
context.on('targetchanged', (target) => {
context.on('targetchanged', target => {
return events.push('CHANGED: ' + target.url());
});
context.on('targetdestroyed', (target) => {
context.on('targetdestroyed', target => {
return events.push('DESTROYED: ' + target.url());
});
const page = await context.newPage();
@ -105,14 +105,14 @@ describe('BrowserContext', function () {
const context = await browser.createIncognitoBrowserContext();
let resolved = false;
const targetPromise = context.waitForTarget((target) => {
const targetPromise = context.waitForTarget(target => {
return target.url() === server.EMPTY_PAGE;
});
targetPromise
.then(() => {
return (resolved = true);
})
.catch((error) => {
.catch(error => {
resolved = true;
if (error instanceof puppeteer.errors.TimeoutError) {
console.error(error);
@ -142,14 +142,14 @@ describe('BrowserContext', function () {
const context = await browser.createIncognitoBrowserContext();
const error = await context
.waitForTarget(
(target) => {
target => {
return target.url() === server.EMPTY_PAGE;
},
{
timeout: 1,
}
)
.catch((error_) => {
.catch(error_ => {
return error_;
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);

View File

@ -71,7 +71,7 @@ describeChromeOnly('Chromium-Specific Launcher tests', function () {
browserURL,
browserWSEndpoint: originalBrowser.wsEndpoint(),
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain(
@ -91,7 +91,7 @@ describeChromeOnly('Chromium-Specific Launcher tests', function () {
const browserURL = 'http://127.0.0.1:32333';
let error!: Error;
await puppeteer.connect({ browserURL }).catch((error_) => {
await puppeteer.connect({browserURL}).catch(error_ => {
return (error = error_);
});
expect(error.message).toContain(
@ -128,7 +128,7 @@ describeChromeOnly('Chromium-Specific Launcher tests', function () {
const {defaultBrowserOptions, puppeteer} = getTestState();
const options = Object.assign({pipe: true}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
const disconnectedEventPromise = new Promise((resolve) => {
const disconnectedEventPromise = new Promise(resolve => {
return browser.once('disconnected', resolve);
});
// Emulate user exiting browser.
@ -159,7 +159,7 @@ describeChromeOnly('Chromium-Specific Page Tests', function () {
});
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
await page.goto(server.PREFIX + '/intervention');

View File

@ -163,7 +163,7 @@ describe('Page.click', function () {
await page.goto(server.PREFIX + '/offscreenbuttons.html');
const messages: any[] = [];
page.on('console', (msg) => {
page.on('console', msg => {
return messages.push(msg.text());
});
for (let i = 0; i < 11; ++i) {
@ -270,7 +270,7 @@ describe('Page.click', function () {
await page.goto(server.PREFIX + '/input/button.html');
let error!: Error;
await page.click('button.does-not-exist').catch((error_) => {
await page.click('button.does-not-exist').catch(error_ => {
return (error = error_);
});
expect(error.message).toBe(

View File

@ -240,7 +240,7 @@ describe('Cookie specs', () => {
const cookieStrings = await page.evaluate(() => {
const cookies = document.cookie.split(';');
return cookies
.map((cookie) => {
.map(cookie => {
return cookie.trim();
})
.sort();
@ -430,9 +430,9 @@ describe('Cookie specs', () => {
await page.goto(server.PREFIX + '/grid.html');
await page.setCookie({name: 'localhost-cookie', value: 'best'});
await page.evaluate<(src: string) => Promise<void>>((src) => {
await page.evaluate<(src: string) => Promise<void>>(src => {
let fulfill!: () => void;
const promise = new Promise<void>((x) => {
const promise = new Promise<void>(x => {
return (fulfill = x);
});
const iframe = document.createElement('iframe') as HTMLIFrameElement;
@ -488,8 +488,7 @@ describe('Cookie specs', () => {
itFailsFirefox(
'should set secure same-site cookies from a frame',
async () => {
const { httpsServer, puppeteer, defaultBrowserOptions } =
getTestState();
const {httpsServer, puppeteer, defaultBrowserOptions} = getTestState();
const browser = await puppeteer.launch({
...defaultBrowserOptions,
@ -500,9 +499,9 @@ describe('Cookie specs', () => {
try {
await page.goto(httpsServer.PREFIX + '/grid.html');
await page.evaluate<(src: string) => Promise<void>>((src) => {
await page.evaluate<(src: string) => Promise<void>>(src => {
let fulfill!: () => void;
const promise = new Promise<void>((x) => {
const promise = new Promise<void>(x => {
return (fulfill = x);
});
const iframe = document.createElement('iframe');

View File

@ -65,7 +65,7 @@ describe('Coverage specs', function () {
await page.goto(server.PREFIX + '/jscoverage/eval.html');
const coverage = await page.coverage.stopJSCoverage();
expect(
coverage.find((entry) => {
coverage.find(entry => {
return entry.url.startsWith('debugger://');
})
).not.toBe(null);
@ -287,14 +287,14 @@ describe('Coverage specs', function () {
const {page, server} = getTestState();
await page.coverage.startCSSCoverage();
await page.evaluate<(url: string) => Promise<void>>(async (url) => {
await page.evaluate<(url: string) => Promise<void>>(async url => {
document.body.textContent = 'hello, world';
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
document.head.appendChild(link);
await new Promise((x) => {
await new Promise(x => {
return (link.onload = x);
});
}, server.PREFIX + '/csscoverage/stylesheet1.css');

View File

@ -30,7 +30,7 @@ describe('Page.Events.Dialog', function () {
it('should fire', async () => {
const {page} = getTestState();
const onDialog = sinon.stub().callsFake((dialog) => {
const onDialog = sinon.stub().callsFake(dialog => {
dialog.accept();
});
page.on('dialog', onDialog);
@ -49,7 +49,7 @@ describe('Page.Events.Dialog', function () {
itFailsFirefox('should allow accepting prompts', async () => {
const {page} = getTestState();
const onDialog = sinon.stub().callsFake((dialog) => {
const onDialog = sinon.stub().callsFake(dialog => {
dialog.accept('answer!');
});
page.on('dialog', onDialog);
@ -69,7 +69,7 @@ describe('Page.Events.Dialog', function () {
it('should dismiss the prompt', async () => {
const {page} = getTestState();
page.on('dialog', (dialog) => {
page.on('dialog', dialog => {
dialog.dismiss();
});
const result = await page.evaluate(() => {

View File

@ -209,7 +209,7 @@ describe('ElementHandle specs', function () {
return document.querySelector('button')!.firstChild;
});
let error!: Error;
await buttonTextNode.click().catch((error_) => {
await buttonTextNode.click().catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Node is not of type HTMLElement');
@ -223,7 +223,7 @@ describe('ElementHandle specs', function () {
return button.remove();
}, button);
let error!: Error;
await button.click().catch((error_) => {
await button.click().catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Node is detached from document');
@ -236,7 +236,7 @@ describe('ElementHandle specs', function () {
await page.evaluate((button: HTMLElement) => {
return (button.style.display = 'none');
}, button);
const error = await button.click().catch((error_) => {
const error = await button.click().catch(error_ => {
return error_;
});
expect(error.message).toBe(
@ -251,7 +251,7 @@ describe('ElementHandle specs', function () {
await page.evaluate((button: HTMLElement) => {
return (button.parentElement!.style.display = 'none');
}, button);
const error = await button.click().catch((error_) => {
const error = await button.click().catch(error_ => {
return error_;
});
expect(error.message).toBe(
@ -263,7 +263,7 @@ describe('ElementHandle specs', function () {
await page.setContent('hello<br>goodbye');
const br = (await page.$('br'))!;
const error = await br.click().catch((error_) => {
const error = await br.click().catch(error_ => {
return error_;
});
expect(error.message).toBe(
@ -284,13 +284,13 @@ describe('ElementHandle specs', function () {
expect(element).toBeDefined();
const innerWaitFor = element.waitForSelector('.bar');
await element.evaluate((el) => {
await element.evaluate(el => {
el.innerHTML = '<div class="bar">bar1</div>';
});
element = (await innerWaitFor)!;
expect(element).toBeDefined();
expect(
await element.evaluate((el) => {
await element.evaluate(el => {
return (el as HTMLElement).innerText;
})
).toStrictEqual('bar1');
@ -316,13 +316,13 @@ describe('ElementHandle specs', function () {
const el2 = (await page.waitForSelector('#el1'))!;
expect(
await (await el2.waitForXPath('//div'))!.evaluate((el) => {
await (await el2.waitForXPath('//div'))!.evaluate(el => {
return el.id;
})
).toStrictEqual('el2');
expect(
await (await el2.waitForXPath('.//div'))!.evaluate((el) => {
await (await el2.waitForXPath('.//div'))!.evaluate(el => {
return el.id;
})
).toStrictEqual('el2');
@ -401,7 +401,7 @@ describe('ElementHandle specs', function () {
});
const element = (await page.$('getById/foo'))!;
expect(
await page.evaluate<(element: HTMLElement) => string>((element) => {
await page.evaluate<(element: HTMLElement) => string>(element => {
return element.id;
}, element)
).toBe('foo');
@ -453,9 +453,9 @@ describe('ElementHandle specs', function () {
});
const elements = await page.$$('getByClass/foo');
const classNames = await Promise.all(
elements.map(async (element) => {
elements.map(async element => {
return await page.evaluate<(element: HTMLElement) => string>(
(element) => {
element => {
return element.className;
},
element
@ -475,7 +475,7 @@ describe('ElementHandle specs', function () {
return document.querySelectorAll(`.${selector}`);
},
});
const elements = await page.$$eval('getByClass/foo', (divs) => {
const elements = await page.$$eval('getByClass/foo', divs => {
return divs.length;
});
@ -517,14 +517,14 @@ describe('ElementHandle specs', function () {
const innerWaitFor = element.waitForSelector('getByClass/bar');
await element.evaluate((el) => {
await element.evaluate(el => {
el.innerHTML = '<div class="bar">bar1</div>';
});
element = (await innerWaitFor)!;
expect(element).toBeDefined();
expect(
await element.evaluate((el) => {
await element.evaluate(el => {
return (el as HTMLElement).innerText;
})
).toStrictEqual('bar1');
@ -583,14 +583,14 @@ describe('ElementHandle specs', function () {
},
});
const txtContent = await page.$eval('getByClass/foo', (div) => {
const txtContent = await page.$eval('getByClass/foo', div => {
return div.textContent;
});
expect(txtContent).toBe('text');
const txtContents = await page.$$eval('getByClass/foo', (divs) => {
const txtContents = await page.$$eval('getByClass/foo', divs => {
return divs
.map((d) => {
.map(d => {
return d.textContent;
})
.join('');

View File

@ -91,7 +91,7 @@ describe('Emulation', () => {
function dispatchTouch() {
let fulfill!: (value: string) => void;
const promise = new Promise((x) => {
const promise = new Promise(x => {
fulfill = x;
});
window.ontouchstart = () => {
@ -232,7 +232,7 @@ describe('Emulation', () => {
const {page} = getTestState();
let error!: Error;
await page.emulateMediaType('bad').catch((error_) => {
await page.emulateMediaType('bad').catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Unsupported media type: bad');
@ -363,7 +363,7 @@ describe('Emulation', () => {
let error!: Error;
await page
.emulateMediaFeatures([{name: 'bad', value: ''}])
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Unsupported media feature: bad');
@ -414,11 +414,11 @@ describe('Emulation', () => {
const {page} = getTestState();
let error!: Error;
await page.emulateTimezone('Foo/Bar').catch((error_) => {
await page.emulateTimezone('Foo/Bar').catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Invalid timezone ID: Foo/Bar');
await page.emulateTimezone('Baz/Qux').catch((error_) => {
await page.emulateTimezone('Baz/Qux').catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Invalid timezone ID: Baz/Qux');
@ -482,7 +482,7 @@ describe('Emulation', () => {
await page
// @ts-expect-error deliberately passign invalid deficiency
.emulateVisionDeficiency('invalid')
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Unsupported vision deficiency: invalid');

View File

@ -50,7 +50,7 @@ describe('Evaluation specs', function () {
it('should transfer NaN', async () => {
const {page} = getTestState();
const result = await page.evaluate((a) => {
const result = await page.evaluate(a => {
return a;
}, NaN);
expect(Object.is(result, NaN)).toBe(true);
@ -58,7 +58,7 @@ describe('Evaluation specs', function () {
it('should transfer -0', async () => {
const {page} = getTestState();
const result = await page.evaluate((a) => {
const result = await page.evaluate(a => {
return a;
}, -0);
expect(Object.is(result, -0)).toBe(true);
@ -66,7 +66,7 @@ describe('Evaluation specs', function () {
it('should transfer Infinity', async () => {
const {page} = getTestState();
const result = await page.evaluate((a) => {
const result = await page.evaluate(a => {
return a;
}, Infinity);
expect(Object.is(result, Infinity)).toBe(true);
@ -74,7 +74,7 @@ describe('Evaluation specs', function () {
it('should transfer -Infinity', async () => {
const {page} = getTestState();
const result = await page.evaluate((a) => {
const result = await page.evaluate(a => {
return a;
}, -Infinity);
expect(Object.is(result, -Infinity)).toBe(true);
@ -83,7 +83,7 @@ describe('Evaluation specs', function () {
const {page} = getTestState();
const result = await page.evaluate(
(a) => {
a => {
return a;
},
[1, 2, 3]
@ -94,7 +94,7 @@ describe('Evaluation specs', function () {
const {page} = getTestState();
const result = await page.evaluate(
(a) => {
a => {
return Array.isArray(a);
},
[1, 2, 3]
@ -146,7 +146,7 @@ describe('Evaluation specs', function () {
const {page} = getTestState();
const result = await page.evaluate(
(a) => {
a => {
return a['中文字符'];
},
{
@ -164,7 +164,7 @@ describe('Evaluation specs', function () {
location.reload();
return new Promise(() => {});
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('Protocol error');
@ -181,7 +181,7 @@ describe('Evaluation specs', function () {
const {page, server} = getTestState();
let frameEvaluation = null;
page.on('framenavigated', async (frame) => {
page.on('framenavigated', async frame => {
frameEvaluation = frame.evaluate(() => {
return 6 * 7;
});
@ -219,7 +219,7 @@ describe('Evaluation specs', function () {
// @ts-expect-error we know the object doesn't exist
return notExistingObject.property;
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -233,7 +233,7 @@ describe('Evaluation specs', function () {
.evaluate(() => {
throw 'qwerty';
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -247,7 +247,7 @@ describe('Evaluation specs', function () {
.evaluate(() => {
throw 100500;
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -257,7 +257,7 @@ describe('Evaluation specs', function () {
const {page} = getTestState();
const object = {foo: 'bar!'};
const result = await page.evaluate((a) => {
const result = await page.evaluate(a => {
return a;
}, object);
expect(result).not.toBe(object);
@ -353,16 +353,14 @@ describe('Evaluation specs', function () {
const windowHandle = await page.evaluateHandle(() => {
return window;
});
const errorText = await windowHandle
.jsonValue<string>()
.catch((error_) => {
const errorText = await windowHandle.jsonValue<string>().catch(error_ => {
return error_.message;
});
const error = await page
.evaluate<(errorText: string) => Error>((errorText) => {
.evaluate<(errorText: string) => Error>(errorText => {
throw new Error(errorText);
}, errorText)
.catch((error_) => {
.catch(error_ => {
return error_;
});
expect(error.message).toContain(errorText);
@ -390,7 +388,7 @@ describe('Evaluation specs', function () {
await page.setContent('<section>42</section>');
const element = (await page.$('section'))!;
const text = await page.evaluate((e) => {
const text = await page.evaluate(e => {
return e.textContent;
}, element);
expect(text).toBe('42');
@ -407,7 +405,7 @@ describe('Evaluation specs', function () {
.evaluate((e: HTMLElement) => {
return e.textContent;
}, element)
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('JSHandle is disposed');
@ -424,7 +422,7 @@ describe('Evaluation specs', function () {
.evaluate((body: HTMLElement) => {
return body.innerHTML;
}, bodyHandle)
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -458,7 +456,7 @@ describe('Evaluation specs', function () {
.evaluate(() => {
return null;
})
.catch((error_) => {
.catch(error_ => {
return error_;
});
expect((error as Error).message).toContain('navigation');
@ -494,7 +492,7 @@ describe('Evaluation specs', function () {
throw new Error('Error in promise');
});
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('Error in promise');
@ -530,7 +528,7 @@ describe('Evaluation specs', function () {
).toBe(123);
// Make sure CSP works.
await page.addScriptTag({ content: 'window.e = 10;' }).catch((error) => {
await page.addScriptTag({content: 'window.e = 10;'}).catch(error => {
return void error;
});
expect(

View File

@ -36,10 +36,10 @@ describe('Fixtures', function () {
puppeteerPath,
JSON.stringify(options),
]);
res.stderr.on('data', (data) => {
res.stderr.on('data', data => {
return (dumpioData += data.toString('utf8'));
});
await new Promise((resolve) => {
await new Promise(resolve => {
return res.on('close', resolve);
});
expect(dumpioData).toContain('message from dumpio');
@ -55,10 +55,10 @@ describe('Fixtures', function () {
puppeteerPath,
JSON.stringify(options),
]);
res.stderr.on('data', (data) => {
res.stderr.on('data', data => {
return (dumpioData += data.toString('utf8'));
});
await new Promise((resolve) => {
await new Promise(resolve => {
return res.on('close', resolve);
});
expect(dumpioData).toContain('DevTools listening on ws://');
@ -77,11 +77,11 @@ describe('Fixtures', function () {
JSON.stringify(options),
]);
let wsEndPointCallback: (value: string) => void;
const wsEndPointPromise = new Promise<string>((x) => {
const wsEndPointPromise = new Promise<string>(x => {
return (wsEndPointCallback = x);
});
let output = '';
res.stdout.on('data', (data) => {
res.stdout.on('data', data => {
output += data;
if (output.indexOf('\n')) {
wsEndPointCallback(output.substring(0, output.indexOf('\n')));
@ -91,10 +91,10 @@ describe('Fixtures', function () {
browserWSEndpoint: await wsEndPointPromise,
});
const promises = [
new Promise((resolve) => {
new Promise(resolve => {
return browser.once('disconnected', resolve);
}),
new Promise((resolve) => {
new Promise(resolve => {
return res.on('close', resolve);
}),
];

View File

@ -94,7 +94,7 @@ describe('Frame specs', function () {
.evaluate(() => {
return 7 * 8;
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain(
@ -110,7 +110,7 @@ describe('Frame specs', function () {
// This test checks if Frame.evaluate allows a readonly array to be an argument.
// See https://github.com/puppeteer/puppeteer/issues/6953.
const readonlyArray: readonly string[] = ['a', 'b', 'c'];
await mainFrame.evaluate((arr) => {
await mainFrame.evaluate(arr => {
return arr;
}, readonlyArray);
});
@ -137,7 +137,7 @@ describe('Frame specs', function () {
await page.goto(server.EMPTY_PAGE);
// validate frameattached events
const attachedFrames: Frame[] = [];
page.on('frameattached', (frame) => {
page.on('frameattached', frame => {
return attachedFrames.push(frame);
});
await utils.attachFrame(page, 'frame1', './assets/frame.html');
@ -146,7 +146,7 @@ describe('Frame specs', function () {
// validate framenavigated events
const navigatedFrames: Frame[] = [];
page.on('framenavigated', (frame) => {
page.on('framenavigated', frame => {
return navigatedFrames.push(frame);
});
await utils.navigateFrame(page, 'frame1', './empty.html');
@ -155,7 +155,7 @@ describe('Frame specs', function () {
// validate framedetached events
const detachedFrames: Frame[] = [];
page.on('framedetached', (frame) => {
page.on('framedetached', frame => {
return detachedFrames.push(frame);
});
await utils.detachFrame(page, 'frame1');
@ -200,13 +200,13 @@ describe('Frame specs', function () {
let attachedFrames = [];
let detachedFrames = [];
let navigatedFrames = [];
page.on('frameattached', (frame) => {
page.on('frameattached', frame => {
return attachedFrames.push(frame);
});
page.on('framedetached', (frame) => {
page.on('framedetached', frame => {
return detachedFrames.push(frame);
});
page.on('framenavigated', (frame) => {
page.on('framenavigated', frame => {
return navigatedFrames.push(frame);
});
await page.goto(server.PREFIX + '/frames/nested-frames.html');
@ -228,13 +228,13 @@ describe('Frame specs', function () {
let attachedFrames = [];
let detachedFrames = [];
let navigatedFrames = [];
page.on('frameattached', (frame) => {
page.on('frameattached', frame => {
return attachedFrames.push(frame);
});
page.on('framedetached', (frame) => {
page.on('framedetached', frame => {
return detachedFrames.push(frame);
});
page.on('framenavigated', (frame) => {
page.on('framenavigated', frame => {
return navigatedFrames.push(frame);
});
await page.goto(server.PREFIX + '/frames/frameset.html');
@ -258,7 +258,7 @@ describe('Frame specs', function () {
const frame = document.createElement('iframe');
frame.src = url;
document.body.shadowRoot!.appendChild(frame);
await new Promise((x) => {
await new Promise(x => {
return (frame.onload = x);
});
}, server.EMPTY_PAGE);
@ -274,7 +274,7 @@ describe('Frame specs', function () {
frame.name = 'theFrameName';
frame.src = url;
document.body.appendChild(frame);
return new Promise((x) => {
return new Promise(x => {
return (frame.onload = x);
});
}, server.EMPTY_PAGE);
@ -333,7 +333,7 @@ describe('Frame specs', function () {
await page.goto(server.PREFIX + '/frames/lazy-frame.html');
expect(
page.frames().map((frame) => {
page.frames().map(frame => {
return frame._hasStartedLoading;
})
).toEqual([true, true, false]);

View File

@ -166,7 +166,7 @@ describeChromeOnly('headful tests', function () {
);
},
});
const devtoolsPageTarget = await browser.waitForTarget((target) => {
const devtoolsPageTarget = await browser.waitForTarget(target => {
return target.type() === 'other';
});
const page = (await devtoolsPageTarget.page())!;
@ -238,7 +238,7 @@ describeChromeOnly('headful tests', function () {
const frame = document.createElement('iframe');
frame.setAttribute('src', 'https://google.com/');
document.body.appendChild(frame);
return new Promise((x) => {
return new Promise(x => {
return (frame.onload = x);
});
});
@ -307,7 +307,7 @@ describeChromeOnly('headful tests', function () {
});
await browser.close();
const requests = networkEvents.map((event) => {
const requests = networkEvents.map(event => {
return event.request.url;
});
expect(requests).toContain(`http://oopifdomain:${server.PORT}/fetch`);
@ -407,7 +407,7 @@ describeChromeOnly('headful tests', function () {
expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`);
}
await Promise.all(
pages.map((page) => {
pages.map(page => {
return page.close();
})
);

View File

@ -92,7 +92,7 @@ describe('ignoreHTTPSErrors', function () {
httpsServer.setRedirect('/plzredirect', '/empty.html');
const responses: HTTPResponse[] = [];
page.on('response', (response) => {
page.on('response', response => {
return responses.push(response);
});
const [serverRequest] = await Promise.all([
@ -113,7 +113,7 @@ describe('ignoreHTTPSErrors', function () {
const {httpsServer} = getTestState();
let error!: Error;
const response = await page.goto(httpsServer.EMPTY_PAGE).catch((error_) => {
const response = await page.goto(httpsServer.EMPTY_PAGE).catch(error_ => {
return (error = error_);
});
expect(error).toBeUndefined();
@ -123,7 +123,7 @@ describe('ignoreHTTPSErrors', function () {
const {httpsServer} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
const response = (await page.goto(httpsServer.EMPTY_PAGE))!;

View File

@ -38,10 +38,10 @@ describe('input tests', function () {
const input = (await page.$('input'))!;
await page.evaluate((e: HTMLElement) => {
(globalThis as any)._inputEvents = [];
e.addEventListener('change', (ev) => {
e.addEventListener('change', ev => {
return (globalThis as any)._inputEvents.push(ev.type);
});
e.addEventListener('input', (ev) => {
e.addEventListener('input', ev => {
return (globalThis as any)._inputEvents.push(ev.type);
});
}, input);
@ -64,7 +64,7 @@ describe('input tests', function () {
expect(
await page.evaluate((e: HTMLInputElement) => {
const reader = new FileReader();
const promise = new Promise((fulfill) => {
const promise = new Promise(fulfill => {
return (reader.onload = fulfill);
});
reader.readAsText(e.files![0]!);
@ -104,7 +104,7 @@ describe('input tests', function () {
const {page, puppeteer} = getTestState();
let error!: Error;
await page.waitForFileChooser({ timeout: 1 }).catch((error_) => {
await page.waitForFileChooser({timeout: 1}).catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -114,7 +114,7 @@ describe('input tests', function () {
page.setDefaultTimeout(1);
let error!: Error;
await page.waitForFileChooser().catch((error_) => {
await page.waitForFileChooser().catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -124,7 +124,7 @@ describe('input tests', function () {
page.setDefaultTimeout(0);
let error!: Error;
await page.waitForFileChooser({ timeout: 1 }).catch((error_) => {
await page.waitForFileChooser({timeout: 1}).catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -151,7 +151,7 @@ describe('input tests', function () {
const [fileChooser1, fileChooser2] = await Promise.all([
page.waitForFileChooser(),
page.waitForFileChooser(),
page.$eval('input', (input) => {
page.$eval('input', input => {
return (input as HTMLInputElement).click();
}),
]);
@ -172,17 +172,17 @@ describe('input tests', function () {
]);
await Promise.all([
chooser.accept([FILE_TO_UPLOAD]),
new Promise((x) => {
new Promise(x => {
return page.once('metrics', x);
}),
]);
expect(
await page.$eval('input', (input) => {
await page.$eval('input', input => {
return (input as HTMLInputElement).files!.length;
})
).toBe(1);
expect(
await page.$eval('input', (input) => {
await page.$eval('input', input => {
return (input as HTMLInputElement).files![0]!.name;
})
).toBe('file-to-upload.txt');
@ -191,18 +191,18 @@ describe('input tests', function () {
const {page} = getTestState();
await page.setContent(`<input type=file>`);
page.waitForFileChooser().then((chooser) => {
page.waitForFileChooser().then(chooser => {
return chooser.accept([FILE_TO_UPLOAD]);
});
expect(
await page.$eval('input', async (picker) => {
await page.$eval('input', async picker => {
const pick = picker as HTMLInputElement;
pick.click();
await new Promise((x) => {
await new Promise(x => {
return (pick.oninput = x);
});
const reader = new FileReader();
const promise = new Promise((fulfill) => {
const promise = new Promise(fulfill => {
return (reader.onload = fulfill);
});
reader.readAsText(pick.files![0]!);
@ -216,27 +216,27 @@ describe('input tests', function () {
const {page} = getTestState();
await page.setContent(`<input type=file>`);
page.waitForFileChooser().then((chooser) => {
page.waitForFileChooser().then(chooser => {
return chooser.accept([FILE_TO_UPLOAD]);
});
expect(
await page.$eval('input', async (picker) => {
await page.$eval('input', async picker => {
const pick = picker as HTMLInputElement;
pick.click();
await new Promise((x) => {
await new Promise(x => {
return (pick.oninput = x);
});
return pick.files!.length;
})
).toBe(1);
page.waitForFileChooser().then((chooser) => {
page.waitForFileChooser().then(chooser => {
return chooser.accept([]);
});
expect(
await page.$eval('input', async (picker) => {
await page.$eval('input', async picker => {
const pick = picker as HTMLInputElement;
pick.click();
await new Promise((x) => {
await new Promise(x => {
return (pick.oninput = x);
});
return pick.files!.length;
@ -260,7 +260,7 @@ describe('input tests', function () {
),
path.relative(process.cwd(), __dirname + '/../assets/pptr.png'),
])
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).not.toBe(null);
@ -274,7 +274,7 @@ describe('input tests', function () {
page.click('input'),
]);
let error!: Error;
await chooser.accept(['file-does-not-exist.txt']).catch((error_) => {
await chooser.accept(['file-does-not-exist.txt']).catch(error_ => {
return (error = error_);
});
expect(error).toBeUndefined();
@ -283,18 +283,18 @@ describe('input tests', function () {
const {page} = getTestState();
await page.setContent(`<input type=file>`);
page.waitForFileChooser().then((chooser) => {
page.waitForFileChooser().then(chooser => {
return chooser.accept(['file-does-not-exist.txt']);
});
expect(
await page.$eval('input', async (picker) => {
await page.$eval('input', async picker => {
const pick = picker as HTMLInputElement;
pick.click();
await new Promise((x) => {
await new Promise(x => {
return (pick.oninput = x);
});
const reader = new FileReader();
const promise = new Promise((fulfill) => {
const promise = new Promise(fulfill => {
return (reader.onerror = fulfill);
});
reader.readAsText(pick.files![0]!);
@ -310,13 +310,13 @@ describe('input tests', function () {
await page.setContent(`<input type=file>`);
const [fileChooser] = await Promise.all([
page.waitForFileChooser(),
page.$eval('input', (input) => {
page.$eval('input', input => {
return (input as HTMLInputElement).click();
}),
]);
await fileChooser.accept([]);
let error!: Error;
await fileChooser.accept([]).catch((error_) => {
await fileChooser.accept([]).catch(error_ => {
return (error = error_);
});
expect(error.message).toBe(
@ -335,7 +335,7 @@ describe('input tests', function () {
await page.setContent(`<input type=file>`);
const [fileChooser1] = await Promise.all([
page.waitForFileChooser(),
page.$eval('input', (input) => {
page.$eval('input', input => {
return (input as HTMLInputElement).click();
}),
]);
@ -343,7 +343,7 @@ describe('input tests', function () {
// If this resolves, than we successfully canceled file chooser.
await Promise.all([
page.waitForFileChooser(),
page.$eval('input', (input) => {
page.$eval('input', input => {
return (input as HTMLInputElement).click();
}),
]);
@ -354,7 +354,7 @@ describe('input tests', function () {
await page.setContent(`<input type=file>`);
const [fileChooser] = await Promise.all([
page.waitForFileChooser(),
page.$eval('input', (input) => {
page.$eval('input', input => {
return (input as HTMLElement).click();
}),
]);

View File

@ -54,7 +54,7 @@ describe('JSHandle', function () {
const aHandle = await page.evaluateHandle(() => {
return 5;
});
const isFive = await page.evaluate((e) => {
const isFive = await page.evaluate(e => {
return Object.is(e, 5);
}, aHandle);
expect(isFive).toBeTruthy();
@ -67,13 +67,13 @@ describe('JSHandle', function () {
let error!: Error;
await page
.evaluateHandle(
(opts) => {
opts => {
return opts.elem;
},
// @ts-expect-error we are deliberately passing a bad type here (nested object)
{test}
)
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('Recursive objects are not allowed.');
@ -85,7 +85,7 @@ describe('JSHandle', function () {
return Infinity;
});
expect(
await page.evaluate((e) => {
await page.evaluate(e => {
return Object.is(e, Infinity);
}, aHandle)
).toBe(true);
@ -181,7 +181,7 @@ describe('JSHandle', function () {
const windowHandle = await page.evaluateHandle('window');
let error!: Error;
await windowHandle.jsonValue().catch((error_) => {
await windowHandle.jsonValue().catch(error_ => {
return (error = error_);
});
if (isChrome) {
@ -358,7 +358,7 @@ describe('JSHandle', function () {
`;
});
await page.evaluate(async () => {
return new Promise((resolve) => {
return new Promise(resolve => {
return window.requestAnimationFrame(resolve);
});
});
@ -388,7 +388,7 @@ describe('JSHandle', function () {
`;
});
await page.evaluate(async () => {
return new Promise((resolve) => {
return new Promise(resolve => {
return window.requestAnimationFrame(resolve);
});
});
@ -426,7 +426,7 @@ describe('JSHandle', function () {
document.body.innerHTML = `
<div style="cursor: pointer; width: 120px; height: 60px; margin: 30px; padding: 15px;"></div>
`;
document.body.addEventListener('click', (e) => {
document.body.addEventListener('click', e => {
(window as any).reportClick(e.clientX, e.clientY);
});
});

View File

@ -49,8 +49,8 @@ describe('Keyboard', function () {
const {page, isFirefox} = getTestState();
await page.evaluate(() => {
(window as any).keyPromise = new Promise((resolve) => {
return document.addEventListener('keydown', (event) => {
(window as any).keyPromise = new Promise(resolve => {
return document.addEventListener('keydown', event => {
return resolve(event.key);
});
});
@ -106,7 +106,7 @@ describe('Keyboard', function () {
await page.evaluate(() => {
return window.addEventListener(
'keydown',
(e) => {
e => {
return e.preventDefault();
},
true
@ -149,7 +149,7 @@ describe('Keyboard', function () {
await page.evaluate(() => {
return window.addEventListener(
'keydown',
(e) => {
e => {
return e.preventDefault();
},
true
@ -333,7 +333,7 @@ describe('Keyboard', function () {
await page.evaluate(() => {
window.addEventListener(
'keydown',
(event) => {
event => {
event.stopPropagation();
event.stopImmediatePropagation();
if (event.key === 'l') {
@ -361,7 +361,7 @@ describe('Keyboard', function () {
await page.evaluate(() => {
return document.querySelector('textarea')!.addEventListener(
'keydown',
(e) => {
e => {
return ((globalThis as any).lastEvent = e);
},
true
@ -417,7 +417,7 @@ describe('Keyboard', function () {
await page.evaluate(() => {
window.addEventListener(
'keydown',
(event) => {
event => {
return ((globalThis as any).keyLocation = event.location);
},
true
@ -443,19 +443,19 @@ describe('Keyboard', function () {
let error = await page.keyboard
// @ts-expect-error bad input
.press('NotARealKey')
.catch((error_) => {
.catch(error_ => {
return error_;
});
expect(error.message).toBe('Unknown key: "NotARealKey"');
// @ts-expect-error bad input
error = await page.keyboard.press('ё').catch((error_) => {
error = await page.keyboard.press('ё').catch(error_ => {
return error_;
});
expect(error && error.message).toBe('Unknown key: "ё"');
// @ts-expect-error bad input
error = await page.keyboard.press('😊').catch((error_) => {
error = await page.keyboard.press('😊').catch(error_ => {
return error_;
});
expect(error && error.message).toBe('Unknown key: "😊"');
@ -466,7 +466,7 @@ describe('Keyboard', function () {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.type('textarea', '👹 Tokyo street Japan 🇯🇵');
expect(
await page.$eval('textarea', (textarea) => {
await page.$eval('textarea', textarea => {
return (textarea as HTMLInputElement).value;
})
).toBe('👹 Tokyo street Japan 🇯🇵');
@ -484,7 +484,7 @@ describe('Keyboard', function () {
const textarea = (await frame.$('textarea'))!;
await textarea.type('👹 Tokyo street Japan 🇯🇵');
expect(
await frame.$eval('textarea', (textarea) => {
await frame.$eval('textarea', textarea => {
return (textarea as HTMLInputElement).value;
})
).toBe('👹 Tokyo street Japan 🇯🇵');
@ -494,7 +494,7 @@ describe('Keyboard', function () {
await page.evaluate(() => {
(globalThis as any).result = null;
document.addEventListener('keydown', (event) => {
document.addEventListener('keydown', event => {
(globalThis as any).result = [event.key, event.code, event.metaKey];
});
});

View File

@ -148,7 +148,7 @@ describe('Launcher specs', function () {
const page = await remote.newPage();
const navigationPromise = page
.goto(server.PREFIX + '/one-style.html', {timeout: 60000})
.catch((error_) => {
.catch(error_ => {
return error_;
});
await server.waitForRequest('/one-style.css');
@ -173,7 +173,7 @@ describe('Launcher specs', function () {
const page = await remote.newPage();
const watchdog = page
.waitForSelector('div', {timeout: 60000})
.catch((error_) => {
.catch(error_ => {
return error_;
});
remote.disconnect();
@ -192,10 +192,10 @@ describe('Launcher specs', function () {
});
const newPage = await remote.newPage();
const results = await Promise.all([
newPage.waitForRequest(server.EMPTY_PAGE).catch((error) => {
newPage.waitForRequest(server.EMPTY_PAGE).catch(error => {
return error;
}),
newPage.waitForResponse(server.EMPTY_PAGE).catch((error) => {
newPage.waitForResponse(server.EMPTY_PAGE).catch(error => {
return error;
}),
browser.close(),
@ -218,7 +218,7 @@ describe('Launcher specs', function () {
.evaluate(() => {
return new Promise(() => {});
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
await browser.close();
@ -232,7 +232,7 @@ describe('Launcher specs', function () {
const options = Object.assign({}, defaultBrowserOptions, {
executablePath: 'random-invalid-path',
});
await puppeteer.launch(options).catch((error) => {
await puppeteer.launch(options).catch(error => {
return (waitError = error);
});
expect(waitError.message).toContain('Failed to launch');
@ -401,9 +401,7 @@ describe('Launcher specs', function () {
expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain(
'--profile'
);
expect(puppeteer.defaultArgs({ userDataDir: 'foo' })).toContain(
'foo'
);
expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain('foo');
} else {
expect(puppeteer.defaultArgs()).toContain('-headless');
expect(puppeteer.defaultArgs({headless: false})).not.toContain(
@ -481,7 +479,7 @@ describe('Launcher specs', function () {
it('should have default URL when launching browser', async function () {
const {defaultBrowserOptions, puppeteer} = getTestState();
const browser = await puppeteer.launch(defaultBrowserOptions);
const pages = (await browser.pages()).map((page) => {
const pages = (await browser.pages()).map(page => {
return page.url();
});
expect(pages).toEqual(['about:blank']);
@ -511,7 +509,7 @@ describe('Launcher specs', function () {
timeout: 1,
});
let error!: Error;
await puppeteer.launch(options).catch((error_) => {
await puppeteer.launch(options).catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -577,7 +575,7 @@ describe('Launcher specs', function () {
});
let error!: Error;
await puppeteer.launch(options).catch((error_) => {
await puppeteer.launch(options).catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('either pipe or debugging port');
@ -695,8 +693,7 @@ describe('Launcher specs', function () {
]);
});
it('should support ignoreHTTPSErrors option', async () => {
const { httpsServer, puppeteer, defaultBrowserOptions } =
getTestState();
const {httpsServer, puppeteer, defaultBrowserOptions} = getTestState();
const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
const browserWSEndpoint = originalBrowser.wsEndpoint();
@ -709,7 +706,7 @@ describe('Launcher specs', function () {
let error!: Error;
const [serverRequest, response] = await Promise.all([
httpsServer.waitForRequest('/empty.html'),
page.goto(httpsServer.EMPTY_PAGE).catch((error_) => {
page.goto(httpsServer.EMPTY_PAGE).catch(error_ => {
return (error = error_);
}),
]);
@ -771,7 +768,7 @@ describe('Launcher specs', function () {
const browser = await puppeteer.connect({browserWSEndpoint});
const pages = await browser.pages();
const restoredPage = pages.find((page) => {
const restoredPage = pages.find(page => {
return page.url() === server.PREFIX + '/frames/nested-frames.html';
})!;
expect(utils.dumpFrames(restoredPage.mainFrame())).toEqual([
@ -800,8 +797,8 @@ describe('Launcher specs', function () {
browserWSEndpoint: browserOne.wsEndpoint(),
});
const [page1, page2] = await Promise.all([
new Promise<Page>((x) => {
return browserOne.once('targetcreated', (target) => {
new Promise<Page>(x => {
return browserOne.once('targetcreated', target => {
return x(target.page());
});
}),
@ -830,7 +827,7 @@ describe('Launcher specs', function () {
const browserTwo = await puppeteer.connect({browserWSEndpoint});
const pages = await browserTwo.pages();
const pageTwo = pages.find((page) => {
const pageTwo = pages.find(page => {
return page.url() === server.EMPTY_PAGE;
})!;
await pageTwo.reload();

View File

@ -259,7 +259,7 @@ console.log(
}`
);
process.on('unhandledRejection', (reason) => {
process.on('unhandledRejection', reason => {
throw reason;
});
@ -331,7 +331,7 @@ export const expectCookieEquals = (
const {isChrome} = getTestState();
if (!isChrome) {
// Only keep standard properties when testing on a browser other than Chrome.
expectedCookies = expectedCookies.map((cookie) => {
expectedCookies = expectedCookies.map(cookie => {
return {
domain: cookie.domain,
expires: cookie.expires,
@ -359,7 +359,7 @@ export const shortWaitForArrayToHaveAtLeastNElements = async (
if (data.length >= minLength) {
break;
}
await new Promise((resolve) => {
await new Promise(resolve => {
return setTimeout(resolve, timeout);
});
}

View File

@ -47,8 +47,8 @@ describe('Mouse', function () {
const {page} = getTestState();
await page.evaluate(() => {
(globalThis as any).clickPromise = new Promise((resolve) => {
document.addEventListener('click', (event) => {
(globalThis as any).clickPromise = new Promise(resolve => {
document.addEventListener('click', event => {
resolve({
type: event.type,
detail: event.detail,
@ -165,7 +165,7 @@ describe('Mouse', function () {
await page.evaluate(() => {
return document.querySelector('#button-3')!.addEventListener(
'mousedown',
(e) => {
e => {
return ((globalThis as any).lastEvent = e);
},
true
@ -233,7 +233,7 @@ describe('Mouse', function () {
await page.mouse.move(100, 100);
await page.evaluate(() => {
(globalThis as any).result = [];
document.addEventListener('mousemove', (event) => {
document.addEventListener('mousemove', event => {
(globalThis as any).result.push([event.clientX, event.clientY]);
});
});
@ -254,7 +254,7 @@ describe('Mouse', function () {
await page.setViewport({width: 360, height: 640, isMobile: true});
await page.goto(server.CROSS_PROCESS_PREFIX + '/mobile.html');
await page.evaluate(() => {
document.addEventListener('click', (event) => {
document.addEventListener('click', event => {
(globalThis as any).result = {x: event.clientX, y: event.clientY};
});
});

View File

@ -77,7 +77,7 @@ describe('navigation', function () {
let error!: Error;
await page
.goto(server.PREFIX + '/frames/one-frame.html')
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeUndefined();
@ -90,7 +90,7 @@ describe('navigation', function () {
res.end();
});
let error!: Error;
await page.goto(server.EMPTY_PAGE).catch((error_) => {
await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_);
});
expect(error).not.toBe(null);
@ -150,7 +150,7 @@ describe('navigation', function () {
const {page, isChrome} = getTestState();
let error!: Error;
await page.goto('asdfasdf').catch((error_) => {
await page.goto('asdfasdf').catch(error_ => {
return (error = error_);
});
if (isChrome) {
@ -187,7 +187,7 @@ describe('navigation', function () {
});
let error!: Error;
await page.goto(httpsServer.EMPTY_PAGE).catch((error_) => {
await page.goto(httpsServer.EMPTY_PAGE).catch(error_ => {
return (error = error_);
});
if (isChrome) {
@ -206,9 +206,7 @@ describe('navigation', function () {
server.setRedirect('/redirect/1.html', '/redirect/2.html');
server.setRedirect('/redirect/2.html', '/empty.html');
let error!: Error;
await page
.goto(httpsServer.PREFIX + '/redirect/1.html')
.catch((error_) => {
await page.goto(httpsServer.PREFIX + '/redirect/1.html').catch(error_ => {
return (error = error_);
});
if (isChrome) {
@ -224,7 +222,7 @@ describe('navigation', function () {
await page
// @ts-expect-error purposefully passing an old option
.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle'})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain(
@ -237,7 +235,7 @@ describe('navigation', function () {
let error!: Error;
await page
.goto('http://localhost:44123/non-existing-url')
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
if (isChrome) {
@ -254,7 +252,7 @@ describe('navigation', function () {
let error!: Error;
await page
.goto(server.PREFIX + '/empty.html', {timeout: 1})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('Navigation timeout of 1 ms exceeded');
@ -267,7 +265,7 @@ describe('navigation', function () {
server.setRoute('/empty.html', () => {});
let error!: Error;
page.setDefaultNavigationTimeout(1);
await page.goto(server.PREFIX + '/empty.html').catch((error_) => {
await page.goto(server.PREFIX + '/empty.html').catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('Navigation timeout of 1 ms exceeded');
@ -280,7 +278,7 @@ describe('navigation', function () {
server.setRoute('/empty.html', () => {});
let error!: Error;
page.setDefaultTimeout(1);
await page.goto(server.PREFIX + '/empty.html').catch((error_) => {
await page.goto(server.PREFIX + '/empty.html').catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('Navigation timeout of 1 ms exceeded');
@ -294,7 +292,7 @@ describe('navigation', function () {
let error!: Error;
page.setDefaultTimeout(0);
page.setDefaultNavigationTimeout(1);
await page.goto(server.PREFIX + '/empty.html').catch((error_) => {
await page.goto(server.PREFIX + '/empty.html').catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('Navigation timeout of 1 ms exceeded');
@ -310,7 +308,7 @@ describe('navigation', function () {
});
await page
.goto(server.PREFIX + '/grid.html', {timeout: 0, waitUntil: ['load']})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeUndefined();
@ -388,7 +386,7 @@ describe('navigation', function () {
});
// Wait for the page's 'load' event.
await new Promise((fulfill) => {
await new Promise(fulfill => {
return page.once('load', fulfill);
});
expect(navigationFinished).toBe(false);
@ -428,7 +426,7 @@ describe('navigation', function () {
const {page, server} = getTestState();
let warning = null;
const warningHandler: NodeJS.WarningListener = (w) => {
const warningHandler: NodeJS.WarningListener = w => {
return (warning = w);
};
process.on('warning', warningHandler);
@ -442,7 +440,7 @@ describe('navigation', function () {
const {page} = getTestState();
let warning = null;
const warningHandler: NodeJS.WarningListener = (w) => {
const warningHandler: NodeJS.WarningListener = w => {
return (warning = w);
};
process.on('warning', warningHandler);
@ -458,7 +456,7 @@ describe('navigation', function () {
const {context, server} = getTestState();
let warning = null;
const warningHandler: NodeJS.WarningListener = (w) => {
const warningHandler: NodeJS.WarningListener = w => {
return (warning = w);
};
process.on('warning', warningHandler);
@ -478,7 +476,7 @@ describe('navigation', function () {
const {page} = getTestState();
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request);
});
const dataURL = 'data:text/html,<div>yo</div>';
@ -494,7 +492,7 @@ describe('navigation', function () {
const {page, server} = getTestState();
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request);
});
const response = (await page.goto(server.EMPTY_PAGE + '#hash'))!;
@ -668,8 +666,8 @@ describe('navigation', function () {
server.PREFIX + '/frames/one-frame.html'
);
const frame = await utils.waitEvent(page, 'frameattached');
await new Promise<void>((fulfill) => {
page.on('framenavigated', (f) => {
await new Promise<void>(fulfill => {
page.on('framenavigated', f => {
if (f === frame) {
fulfill();
}
@ -743,12 +741,12 @@ describe('navigation', function () {
const navigationPromise = page
.frames()[1]!
.goto(server.EMPTY_PAGE)
.catch((error_) => {
.catch(error_ => {
return error_;
});
await server.waitForRequest('/empty.html');
await page.$eval('iframe', (frame) => {
await page.$eval('iframe', frame => {
return frame.remove();
});
const error = await navigationPromise;
@ -812,7 +810,7 @@ describe('navigation', function () {
server.setRoute('/empty.html', () => {});
let error!: Error;
const navigationPromise = frame.waitForNavigation().catch((error_) => {
const navigationPromise = frame.waitForNavigation().catch(error_ => {
return (error = error_);
});
await Promise.all([
@ -821,7 +819,7 @@ describe('navigation', function () {
return ((window as any).location = '/empty.html');
}),
]);
await page.$eval('iframe', (frame) => {
await page.$eval('iframe', frame => {
return frame.remove();
});
await navigationPromise;

View File

@ -40,7 +40,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request);
});
(await page.goto(server.EMPTY_PAGE))!;
@ -50,7 +50,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request);
});
(await page.goto(server.EMPTY_PAGE))!;
@ -61,7 +61,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request);
});
(await page.goto(server.EMPTY_PAGE))!;
@ -76,7 +76,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request);
});
(await page.goto(server.EMPTY_PAGE))!;
@ -88,7 +88,7 @@ describe('network', function () {
(await page.goto(server.EMPTY_PAGE))!;
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request);
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -100,13 +100,13 @@ describe('network', function () {
(await page.goto(server.EMPTY_PAGE))!;
let requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request);
});
await page.evaluate(() => {
return fetch('/digits/1.png');
});
requests = requests.filter((request) => {
requests = requests.filter(request => {
return !request.url().includes('favicon');
});
expect(requests.length).toBe(1);
@ -147,7 +147,7 @@ describe('network', function () {
const {page, server} = getTestState();
const initiators = new Map();
page.on('request', (request) => {
page.on('request', request => {
return initiators.set(
request.url().split('/').pop(),
request.initiator()
@ -199,7 +199,7 @@ describe('network', function () {
const {page, server} = getTestState();
const responses = new Map();
page.on('response', (r) => {
page.on('response', r => {
return (
!utils.isFavicon(r.request()) &&
responses.set(r.url().split('/').pop(), r)
@ -230,7 +230,7 @@ describe('network', function () {
const {page, server} = getTestState();
const responses = new Map();
page.on('response', (r) => {
page.on('response', r => {
return (
!utils.isFavicon(r) && responses.set(r.url().split('/').pop(), r)
);
@ -262,7 +262,7 @@ describe('network', function () {
return res.end();
});
let request!: HTTPRequest;
page.on('request', (r) => {
page.on('request', r => {
if (!utils.isFavicon(r)) {
request = r;
}
@ -311,7 +311,7 @@ describe('network', function () {
const redirected = redirectChain[0]!.response()!;
expect(redirected.status()).toBe(302);
let error!: Error;
await redirected.text().catch((error_) => {
await redirected.text().catch(error_ => {
return (error = error_);
});
expect(error.message).toContain(
@ -333,12 +333,12 @@ describe('network', function () {
});
// Setup page to trap response.
let requestFinished = false;
page.on('requestfinished', (r) => {
page.on('requestfinished', r => {
return (requestFinished = requestFinished || r.url().includes('/get'));
});
// send request and wait for server response
const [pageResponse] = await Promise.all([
page.waitForResponse((r) => {
page.waitForResponse(r => {
return !utils.isFavicon(r.request());
}),
page.evaluate(() => {
@ -354,11 +354,11 @@ describe('network', function () {
const responseText = pageResponse.text();
// Write part of the response and wait for it to be flushed.
await new Promise((x) => {
await new Promise(x => {
return serverResponse.write('wor', x);
});
// Finish response.
await new Promise<void>((x) => {
await new Promise<void>(x => {
serverResponse.end('ld!', () => {
return x();
});
@ -409,8 +409,8 @@ describe('network', function () {
res.end('Hello World');
});
const url = server.CROSS_PROCESS_PREFIX + '/test.html';
const responsePromise = new Promise<HTTPResponse>((resolve) => {
page.on('response', (response) => {
const responsePromise = new Promise<HTTPResponse>(resolve => {
page.on('response', response => {
// Get the preflight response.
if (
response.request().method() === 'OPTIONS' &&
@ -422,7 +422,7 @@ describe('network', function () {
});
// Trigger a request with a preflight.
await page.evaluate<(src: string) => void>(async (src) => {
await page.evaluate<(src: string) => void>(async src => {
const response = await fetch(src, {
method: 'POST',
headers: {'x-ping': 'pong'},
@ -465,7 +465,7 @@ describe('network', function () {
it('returns timing information', async () => {
const {page, server} = getTestState();
const responses: HTTPResponse[] = [];
page.on('response', (response) => {
page.on('response', response => {
return responses.push(response);
});
(await page.goto(server.EMPTY_PAGE))!;
@ -479,7 +479,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return requests.push(request);
});
(await page.goto(server.EMPTY_PAGE))!;
@ -495,7 +495,7 @@ describe('network', function () {
const {page, server} = getTestState();
const cached: string[] = [];
page.on('requestservedfromcache', (r) => {
page.on('requestservedfromcache', r => {
return cached.push(r.url().split('/').pop()!);
});
@ -509,7 +509,7 @@ describe('network', function () {
const {page, server} = getTestState();
const responses: HTTPResponse[] = [];
page.on('response', (response) => {
page.on('response', response => {
return responses.push(response);
});
(await page.goto(server.EMPTY_PAGE))!;
@ -530,7 +530,7 @@ describe('network', function () {
const {page, server, isChrome} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.url().endsWith('css')) {
request.abort();
} else {
@ -538,7 +538,7 @@ describe('network', function () {
}
});
const failedRequests: HTTPRequest[] = [];
page.on('requestfailed', (request) => {
page.on('requestfailed', request => {
return failedRequests.push(request);
});
await page.goto(server.PREFIX + '/one-style.html');
@ -559,7 +559,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests: HTTPRequest[] = [];
page.on('requestfinished', (request) => {
page.on('requestfinished', request => {
return requests.push(request);
});
(await page.goto(server.EMPTY_PAGE))!;
@ -589,16 +589,16 @@ describe('network', function () {
const {page, server} = getTestState();
const events: string[] = [];
page.on('request', (request) => {
page.on('request', request => {
return events.push(`${request.method()} ${request.url()}`);
});
page.on('response', (response) => {
page.on('response', response => {
return events.push(`${response.status()} ${response.url()}`);
});
page.on('requestfinished', (request) => {
page.on('requestfinished', request => {
return events.push(`DONE ${request.url()}`);
});
page.on('requestfailed', (request) => {
page.on('requestfailed', request => {
return events.push(`FAIL ${request.url()}`);
});
server.setRedirect('/foo.html', '/empty.html');
@ -628,7 +628,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests = new Map();
page.on('request', (request) => {
page.on('request', request => {
return requests.set(request.url().split('/').pop(), request);
});
server.setRedirect('/rrredirect', '/frames/one-frame.html');
@ -643,7 +643,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests = new Map();
page.on('request', (request) => {
page.on('request', request => {
requests.set(request.url().split('/').pop(), request);
request.continue();
});
@ -660,7 +660,7 @@ describe('network', function () {
const {page, server} = getTestState();
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
return requests.push(request);
});
(await page.goto(server.PREFIX + '/pptr.png'))!;
@ -779,7 +779,7 @@ describe('network', function () {
});
const responses = new Map();
page.on('response', (r) => {
page.on('response', r => {
return responses.set(r.url().split('/').pop(), r);
});
@ -817,8 +817,8 @@ describe('network', function () {
res.end('hello world');
});
const responsePromise = new Promise<HTTPResponse>((resolve) => {
return page.on('response', (response) => {
const responsePromise = new Promise<HTTPResponse>(resolve => {
return page.on('response', response => {
return resolve(response);
});
});
@ -852,10 +852,10 @@ describe('network', function () {
});
await page.goto(httpsServer.PREFIX + '/setcookie.html');
const response = await new Promise<HTTPResponse>((resolve) => {
const response = await new Promise<HTTPResponse>(resolve => {
page.on('response', resolve);
const url = httpsServer.CROSS_PROCESS_PREFIX + '/setcookie.html';
page.evaluate<(src: string) => void>((src) => {
page.evaluate<(src: string) => void>(src => {
const xhr = new XMLHttpRequest();
xhr.open('GET', src);
xhr.send();

View File

@ -63,7 +63,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return frame.url().endsWith('/empty.html');
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -79,7 +79,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
@ -100,7 +100,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -121,10 +121,10 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const frame1Promise = page.waitForFrame((frame) => {
const frame1Promise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
const frame2Promise = page.waitForFrame((frame) => {
const frame2Promise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 2;
});
await utils.attachFrame(
@ -150,7 +150,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -171,7 +171,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -194,7 +194,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
@ -211,7 +211,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
@ -250,7 +250,7 @@ describeChromeOnly('OOPIF', function () {
}
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
@ -281,7 +281,7 @@ describeChromeOnly('OOPIF', function () {
it('should report oopif frames', async () => {
const {server} = getTestState();
const frame = page.waitForFrame((frame) => {
const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html');
});
await page.goto(server.PREFIX + '/dynamic-oopif.html');
@ -293,12 +293,12 @@ describeChromeOnly('OOPIF', function () {
it('should wait for inner OOPIFs', async () => {
const {server} = getTestState();
await page.goto(`http://mainframe:${server.PORT}/main-frame.html`);
const frame2 = await page.waitForFrame((frame) => {
const frame2 = await page.waitForFrame(frame => {
return frame.url().endsWith('inner-frame2.html');
});
expect(oopifs(context).length).toBe(2);
expect(
page.frames().filter((frame) => {
page.frames().filter(frame => {
return frame.isOOPFrame();
}).length
).toBe(2);
@ -312,11 +312,11 @@ describeChromeOnly('OOPIF', function () {
it('should load oopif iframes with subresources and request interception', async () => {
const {server} = getTestState();
const frame = page.waitForFrame((frame) => {
const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html');
});
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
await page.goto(server.PREFIX + '/dynamic-oopif.html');
@ -326,7 +326,7 @@ describeChromeOnly('OOPIF', function () {
it('should support frames within OOP iframes', async () => {
const {server} = getTestState();
const oopIframePromise = page.waitForFrame((frame) => {
const oopIframePromise = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html');
});
await page.goto(server.PREFIX + '/dynamic-oopif.html');
@ -357,7 +357,7 @@ describeChromeOnly('OOPIF', function () {
it('clickablePoint, boundingBox, boxModel should work for elements inside OOPIFs', async () => {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
@ -403,7 +403,7 @@ describeChromeOnly('OOPIF', function () {
it('should detect existing OOPIFs when Puppeteer connects to an existing page', async () => {
const {server, puppeteer} = getTestState();
const frame = page.waitForFrame((frame) => {
const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html');
});
await page.goto(server.PREFIX + '/dynamic-oopif.html');
@ -413,7 +413,7 @@ describeChromeOnly('OOPIF', function () {
const browserURL = 'http://127.0.0.1:21222';
const browser1 = await puppeteer.connect({browserURL});
const target = await browser1.waitForTarget((target) => {
const target = await browser1.waitForTarget(target => {
return target.url().endsWith('dynamic-oopif.html');
});
await target.page();
@ -426,7 +426,7 @@ describeChromeOnly('OOPIF', function () {
await page.setViewport({width: 1000, height: 1000});
expect(
page.frames().map((frame) => {
page.frames().map(frame => {
return frame._hasStartedLoading;
})
).toEqual([true, true, false]);
@ -443,7 +443,7 @@ describeChromeOnly('OOPIF', function () {
server.CROSS_PROCESS_PREFIX + '/empty.html'
);
await page.waitForFrame((frame) => {
await page.waitForFrame(frame => {
return frame.url().endsWith('/empty.html');
});
});
@ -451,7 +451,7 @@ describeChromeOnly('OOPIF', function () {
});
function oopifs(context: BrowserContext) {
return context.targets().filter((target) => {
return context.targets().filter(target => {
return target._getTargetInfo().type === 'iframe';
});
}

View File

@ -45,7 +45,7 @@ describe('Page', function () {
.evaluate(() => {
return new Promise(() => {});
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
}),
newPage.close(),
@ -103,10 +103,10 @@ describe('Page', function () {
const newPage = await context.newPage();
const results = await Promise.all([
newPage.waitForRequest(server.EMPTY_PAGE).catch((error) => {
newPage.waitForRequest(server.EMPTY_PAGE).catch(error => {
return error;
}),
newPage.waitForResponse(server.EMPTY_PAGE).catch((error) => {
newPage.waitForResponse(server.EMPTY_PAGE).catch(error => {
return error;
}),
newPage.close(),
@ -188,7 +188,7 @@ describe('Page', function () {
const {page} = getTestState();
let error!: Error;
page.on('error', (err) => {
page.on('error', err => {
return (error = err);
});
page.goto('chrome://crash').catch(() => {});
@ -202,7 +202,7 @@ describe('Page', function () {
const {page} = getTestState();
const [popup] = await Promise.all([
new Promise<Page>((x) => {
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.evaluate(() => {
@ -224,7 +224,7 @@ describe('Page', function () {
const {page} = getTestState();
const [popup] = await Promise.all([
new Promise<Page>((x) => {
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.evaluate(() => {
@ -248,7 +248,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank href="/one-style.html">yo</a>');
const [popup] = await Promise.all([
new Promise<Page>((x) => {
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.click('a'),
@ -272,7 +272,7 @@ describe('Page', function () {
'<a target=_blank rel=opener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>((x) => {
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.click('a'),
@ -296,10 +296,10 @@ describe('Page', function () {
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>((x) => {
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.$eval('a', (a) => {
page.$eval('a', a => {
return (a as HTMLAnchorElement).click();
}),
]);
@ -322,7 +322,7 @@ describe('Page', function () {
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>((x) => {
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.click('a'),
@ -343,7 +343,7 @@ describe('Page', function () {
describe('BrowserContext.overridePermissions', function () {
function getPermission(page: Page, name: string) {
return page.evaluate((name: PermissionName) => {
return navigator.permissions.query({ name }).then((result) => {
return navigator.permissions.query({name}).then(result => {
return result.state;
});
}, name);
@ -370,7 +370,7 @@ describe('Page', function () {
await context
// @ts-expect-error purposeful bad input for test
.overridePermissions(server.EMPTY_PAGE, ['foo'])
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Unknown permission: foo');
@ -483,8 +483,8 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE);
await page.setGeolocation({longitude: 10, latitude: 10});
const geolocation = await page.evaluate(() => {
return new Promise((resolve) => {
return navigator.geolocation.getCurrentPosition((position) => {
return new Promise(resolve => {
return navigator.geolocation.getCurrentPosition(position => {
resolve({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
@ -516,7 +516,7 @@ describe('Page', function () {
await page.setOfflineMode(true);
let error!: Error;
await page.goto(server.EMPTY_PAGE).catch((error_) => {
await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -563,7 +563,7 @@ describe('Page', function () {
return objects.length;
}, objectsHandle);
expect(count).toBe(1);
const values = await page.evaluate((objects) => {
const values = await page.evaluate(objects => {
return Array.from(objects[0]!.values());
}, objectsHandle);
expect(values).toEqual(['hello', 'world']);
@ -593,7 +593,7 @@ describe('Page', function () {
});
await prototypeHandle.dispose();
let error!: Error;
await page.queryObjects(prototypeHandle).catch((error_) => {
await page.queryObjects(prototypeHandle).catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Prototype JSHandle is disposed!');
@ -605,7 +605,7 @@ describe('Page', function () {
return 42;
});
let error!: Error;
await page.queryObjects(prototypeHandle).catch((error_) => {
await page.queryObjects(prototypeHandle).catch(error_ => {
return (error = error_);
});
expect(error.message).toBe(
@ -619,7 +619,7 @@ describe('Page', function () {
const {page} = getTestState();
let message!: ConsoleMessage;
page.once('console', (m) => {
page.once('console', m => {
return (message = m);
});
await Promise.all([
@ -645,7 +645,7 @@ describe('Page', function () {
const {page} = getTestState();
const messages: any[] = [];
page.on('console', (msg) => {
page.on('console', msg => {
return messages.push(msg);
});
// All console events will be reported before `page.evaluate` is finished.
@ -660,13 +660,13 @@ describe('Page', function () {
console.log(Promise.resolve('should not wait until resolved!'));
});
expect(
messages.map((msg) => {
messages.map(msg => {
return msg.type();
})
).toEqual(['timeEnd', 'trace', 'dir', 'warning', 'error', 'log']);
expect(messages[0]!.text()).toContain('calling console.time');
expect(
messages.slice(1).map((msg) => {
messages.slice(1).map(msg => {
return msg.text();
})
).toEqual([
@ -681,7 +681,7 @@ describe('Page', function () {
const {page} = getTestState();
let message!: ConsoleMessage;
page.once('console', (msg) => {
page.once('console', msg => {
return (message = msg);
});
await Promise.all([
@ -771,13 +771,13 @@ describe('Page', function () {
'Title',
'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0'
)!;
await new Promise((x) => {
await new Promise(x => {
return (win.onload = x);
});
// 2. In this popup, create an iframe that console.logs a message.
win.document.body.innerHTML = `<iframe src='/consolelog.html'></iframe>`;
const frame = win.document.querySelector('iframe')!;
await new Promise((x) => {
await new Promise(x => {
return (frame.onload = x);
});
// 3. After that, remove the iframe.
@ -786,7 +786,7 @@ describe('Page', function () {
const popupTarget = page
.browserContext()
.targets()
.find((target) => {
.find(target => {
return target !== page.target();
})!;
// 4. Connect to the popup and make sure it doesn't throw.
@ -815,7 +815,7 @@ describe('Page', function () {
const {page} = getTestState();
const metricsPromise = new Promise<{metrics: Metrics; title: string}>(
(fulfill) => {
fulfill => {
return page.once('metrics', fulfill);
}
);
@ -871,7 +871,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([
page.waitForRequest((request) => {
page.waitForRequest(request => {
return request.url() === server.PREFIX + '/digits/2.png';
}),
page.evaluate(() => {
@ -893,7 +893,7 @@ describe('Page', function () {
},
{timeout: 1}
)
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -907,7 +907,7 @@ describe('Page', function () {
.waitForRequest(() => {
return false;
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -956,7 +956,7 @@ describe('Page', function () {
},
{timeout: 1}
)
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -970,7 +970,7 @@ describe('Page', function () {
.waitForResponse(() => {
return false;
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -980,7 +980,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE);
const [response] = await Promise.all([
page.waitForResponse((response) => {
page.waitForResponse(response => {
return response.url() === server.PREFIX + '/digits/2.png';
}),
page.evaluate(() => {
@ -995,7 +995,7 @@ describe('Page', function () {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const [response] = await Promise.all([
page.waitForResponse(async (response) => {
page.waitForResponse(async response => {
return response.url() === server.PREFIX + '/digits/2.png';
}),
page.evaluate(() => {
@ -1030,7 +1030,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE);
let res;
const [t1, t2] = await Promise.all([
page.waitForNetworkIdle().then((r) => {
page.waitForNetworkIdle().then(r => {
res = r;
return Date.now();
}),
@ -1041,11 +1041,11 @@ describe('Page', function () {
fetch('/digits/1.png'),
fetch('/digits/2.png'),
]);
await new Promise((resolve) => {
await new Promise(resolve => {
return setTimeout(resolve, 200);
});
await fetch('/digits/3.png');
await new Promise((resolve) => {
await new Promise(resolve => {
return setTimeout(resolve, 200);
});
await fetch('/digits/4.png');
@ -1062,7 +1062,7 @@ describe('Page', function () {
it('should respect timeout', async () => {
const {page, puppeteer} = getTestState();
let error!: Error;
await page.waitForNetworkIdle({ timeout: 1 }).catch((error_) => {
await page.waitForNetworkIdle({timeout: 1}).catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -1081,7 +1081,7 @@ describe('Page', function () {
fetch('/digits/1.png'),
fetch('/digits/2.png'),
]);
await new Promise((resolve) => {
await new Promise(resolve => {
return setTimeout(resolve, 250);
});
})();
@ -1274,7 +1274,7 @@ describe('Page', function () {
const {page, server} = getTestState();
let error!: Error;
page.once('pageerror', (e) => {
page.once('pageerror', e => {
return (error = e);
});
await Promise.all([
@ -1411,7 +1411,7 @@ describe('Page', function () {
.setContent(`<img src="${server.PREFIX + imgPath}"></img>`, {
timeout: 1,
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -1426,7 +1426,7 @@ describe('Page', function () {
let error!: Error;
await page
.setContent(`<img src="${server.PREFIX + imgPath}"></img>`)
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -1462,7 +1462,7 @@ describe('Page', function () {
await page.setContent('<div>hello world</div>' + '\x7F');
expect(
await page.$eval('div', (div) => {
await page.$eval('div', div => {
return div.textContent;
})
).toBe('hello world');
@ -1472,7 +1472,7 @@ describe('Page', function () {
await page.setContent('<div>aberración</div>');
expect(
await page.$eval('div', (div) => {
await page.$eval('div', div => {
return div.textContent;
})
).toBe('aberración');
@ -1482,7 +1482,7 @@ describe('Page', function () {
await page.setContent('<div>🐥</div>');
expect(
await page.$eval('div', (div) => {
await page.$eval('div', div => {
return div.textContent;
})
).toBe('🐥');
@ -1492,7 +1492,7 @@ describe('Page', function () {
await page.setContent('<div>\n</div>');
expect(
await page.$eval('div', (div) => {
await page.$eval('div', div => {
return div.textContent;
})
).toBe('\n');
@ -1507,7 +1507,7 @@ describe('Page', function () {
await page.goto(server.PREFIX + '/csp.html');
await page
.addScriptTag({content: 'window.__injected = 42;'})
.catch((error) => {
.catch(error => {
return void error;
});
expect(
@ -1535,7 +1535,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE);
await page
.addScriptTag({content: 'window.__injected = 42;'})
.catch((error) => {
.catch(error => {
return void error;
});
expect(
@ -1588,7 +1588,7 @@ describe('Page', function () {
))!;
await frame
.addScriptTag({content: 'window.__injected = 42;'})
.catch((error) => {
.catch(error => {
return void error;
});
expect(
@ -1610,7 +1610,7 @@ describe('Page', function () {
))!;
await frame
.addScriptTag({content: 'window.__injected = 42;'})
.catch((error) => {
.catch(error => {
return void error;
});
expect(
@ -1768,7 +1768,7 @@ describe('Page', function () {
let error!: Error;
await page
.addScriptTag({content: 'window.__injected = 35;'})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -1781,7 +1781,7 @@ describe('Page', function () {
let error!: Error;
await page
.addScriptTag({url: server.CROSS_PROCESS_PREFIX + '/injectedfile.js'})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -1883,7 +1883,7 @@ describe('Page', function () {
let error!: Error;
await page
.addStyleTag({content: 'body { background-color: green; }'})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -1899,7 +1899,7 @@ describe('Page', function () {
.addStyleTag({
url: server.CROSS_PROCESS_PREFIX + '/injectedstyle.css',
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -1925,7 +1925,7 @@ describe('Page', function () {
'data:text/html, <script>var something = "forbidden"</script>'
);
let error!: Error;
await page.evaluate('something').catch((error_) => {
await page.evaluate('something').catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('something is not defined');
@ -2016,7 +2016,7 @@ describe('Page', function () {
await page.goto(server.PREFIX + '/pdf.html');
let error!: Error;
await page.pdf({ timeout: 1 }).catch((_error) => {
await page.pdf({timeout: 1}).catch(_error => {
return (error = _error);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -2069,7 +2069,7 @@ describe('Page', function () {
const {page, server} = getTestState();
await page.goto(server.PREFIX + '/input/select.html');
await page.$eval('select', (select) => {
await page.$eval('select', select => {
return select.addEventListener('input', () => {
return ((window as any).location = '/empty.html');
});
@ -2120,7 +2120,7 @@ describe('Page', function () {
let error!: Error;
await page.goto(server.PREFIX + '/input/select.html');
await page.select('body', '').catch((error_) => {
await page.select('body', '').catch(error_ => {
return (error = error_);
});
expect(error.message).toContain('Element is not a <select> element.');
@ -2176,9 +2176,9 @@ describe('Page', function () {
await page.select('select', 'blue', 'black', 'magenta');
await page.select('select');
expect(
await page.$eval('select', (select) => {
await page.$eval('select', select => {
return Array.from((select as HTMLSelectElement).options).every(
(option) => {
option => {
return !option.selected;
}
);
@ -2192,9 +2192,9 @@ describe('Page', function () {
await page.select('select', 'blue', 'black', 'magenta');
await page.select('select');
expect(
await page.$eval('select', (select) => {
await page.$eval('select', select => {
return Array.from((select as HTMLSelectElement).options).filter(
(option) => {
option => {
return option.selected;
}
)[0]!.value;
@ -2244,8 +2244,8 @@ describe('Page', function () {
itFailsFirefox('should work with window.close', async () => {
const {page, context} = getTestState();
const newPagePromise = new Promise<Page>((fulfill) => {
return context.once('targetcreated', (target) => {
const newPagePromise = new Promise<Page>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target.page());
});
});
@ -2253,7 +2253,7 @@ describe('Page', function () {
return ((window as any)['newPage'] = window.open('about:blank'));
});
const newPage = await newPagePromise;
const closedPromise = new Promise((x) => {
const closedPromise = new Promise(x => {
return newPage.on('close', x);
});
await page.evaluate(() => {
@ -2265,7 +2265,7 @@ describe('Page', function () {
const {context} = getTestState();
const newPage = await context.newPage();
const closedPromise = new Promise((x) => {
const closedPromise = new Promise(x => {
return newPage.on('close', x);
});
await newPage.close();

View File

@ -65,7 +65,7 @@ describeFailsFirefox('request proxy', () => {
method: originalRequest.method,
headers: originalRequest.headers,
},
(proxyResponse) => {
proxyResponse => {
originalResponse.writeHead(
proxyResponse.statusCode as number,
proxyResponse.headers
@ -88,7 +88,7 @@ describeFailsFirefox('request proxy', () => {
await browser.close();
await new Promise((resolve, reject) => {
proxyServer.close((error) => {
proxyServer.close(error => {
if (error) {
reject(error);
} else {

View File

@ -29,7 +29,7 @@ describe('querySelector', function () {
const {page} = getTestState();
await page.setContent('<section id="testAttribute">43543</section>');
const idAttribute = await page.$eval('section', (e) => {
const idAttribute = await page.$eval('section', e => {
return e.id;
});
expect(idAttribute).toBe('testAttribute');
@ -66,10 +66,10 @@ describe('querySelector', function () {
let error!: Error;
await page
.$eval('section', (e) => {
.$eval('section', e => {
return e.id;
})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error.message).toContain(
@ -109,7 +109,7 @@ describe('querySelector', function () {
const {page} = getTestState();
const divs = await page.$$('pierce/.foo');
const text = await Promise.all(
divs.map((div) => {
divs.map(div => {
return div.evaluate((element: Element) => {
return element.textContent;
});
@ -131,7 +131,7 @@ describe('querySelector', function () {
const parentElement = (await page.$('html > div'))!;
const childElements = await parentElement.$$('pierce/div');
const text = await Promise.all(
childElements.map((div) => {
childElements.map(div => {
return div.evaluate((element: Element) => {
return element.textContent;
});
@ -151,7 +151,7 @@ describe('querySelector', function () {
await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>'
);
const divsCount = await page.$$eval('div', (divs) => {
const divsCount = await page.$$eval('div', divs => {
return divs.length;
});
expect(divsCount).toBe(3);
@ -201,7 +201,7 @@ describe('querySelector', function () {
}
`
);
const sum = await page.$$eval('section', (sections) => {
const sum = await page.$$eval('section', sections => {
return sections.reduce((acc, section) => {
return acc + Number(section.textContent);
}, 0);
@ -233,7 +233,7 @@ describe('querySelector', function () {
await page.setContent('<div>A</div><br/><div>B</div>');
const elements = await page.$$('div');
expect(elements.length).toBe(2);
const promises = elements.map((element) => {
const promises = elements.map(element => {
return page.evaluate((e: HTMLElement) => {
return e.textContent;
}, element);
@ -309,7 +309,7 @@ describe('querySelector', function () {
'<html><body><div class="tweet"><div class="like">100</div><div class="retweets">10</div></div></body></html>'
);
const tweet = (await page.$('.tweet'))!;
const content = await tweet.$eval('.like', (node) => {
const content = await tweet.$eval('.like', node => {
return (node as HTMLElement).innerText;
});
expect(content).toBe('100');
@ -322,7 +322,7 @@ describe('querySelector', function () {
'<div class="a">not-a-child-div</div><div id="myId"><div class="a">a-child-div</div></div>';
await page.setContent(htmlContent);
const elementHandle = (await page.$('#myId'))!;
const content = await elementHandle.$eval('.a', (node) => {
const content = await elementHandle.$eval('.a', node => {
return (node as HTMLElement).innerText;
});
expect(content).toBe('a-child-div');
@ -336,10 +336,10 @@ describe('querySelector', function () {
await page.setContent(htmlContent);
const elementHandle = (await page.$('#myId'))!;
const errorMessage = await elementHandle
.$eval('.a', (node) => {
.$eval('.a', node => {
return (node as HTMLElement).innerText;
})
.catch((error) => {
.catch(error => {
return error.message;
});
expect(errorMessage).toBe(
@ -355,8 +355,8 @@ describe('querySelector', function () {
'<html><body><div class="tweet"><div class="like">100</div><div class="like">10</div></div></body></html>'
);
const tweet = (await page.$('.tweet'))!;
const content = await tweet.$$eval('.like', (nodes) => {
return (nodes as HTMLElement[]).map((n) => {
const content = await tweet.$$eval('.like', nodes => {
return (nodes as HTMLElement[]).map(n => {
return n.innerText;
});
});
@ -370,8 +370,8 @@ describe('querySelector', function () {
'<div class="a">not-a-child-div</div><div id="myId"><div class="a">a1-child-div</div><div class="a">a2-child-div</div></div>';
await page.setContent(htmlContent);
const elementHandle = (await page.$('#myId'))!;
const content = await elementHandle.$$eval('.a', (nodes) => {
return (nodes as HTMLElement[]).map((n) => {
const content = await elementHandle.$$eval('.a', nodes => {
return (nodes as HTMLElement[]).map(n => {
return n.innerText;
});
});
@ -385,7 +385,7 @@ describe('querySelector', function () {
'<div class="a">not-a-child-div</div><div id="myId"></div>';
await page.setContent(htmlContent);
const elementHandle = (await page.$('#myId'))!;
const nodesLength = await elementHandle.$$eval('.a', (nodes) => {
const nodesLength = await elementHandle.$$eval('.a', nodes => {
return nodes.length;
});
expect(nodesLength).toBe(0);
@ -402,7 +402,7 @@ describe('querySelector', function () {
const html = (await page.$('html'))!;
const elements = await html.$$('div');
expect(elements.length).toBe(2);
const promises = elements.map((element) => {
const promises = elements.map(element => {
return page.evaluate((e: HTMLElement) => {
return e.textContent;
}, element);
@ -479,7 +479,7 @@ describe('querySelector', function () {
const html = (await page.$('html'))!;
const elements = await html.$$('allArray/div');
expect(elements.length).toBe(2);
const promises = elements.map((element) => {
const promises = elements.map(element => {
return page.evaluate((e: HTMLElement) => {
return e.textContent;
}, element);
@ -503,7 +503,7 @@ describe('querySelector', function () {
await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>'
);
const divsCount = await page.$$eval('allArray/div', (divs) => {
const divsCount = await page.$$eval('allArray/div', divs => {
return divs.length;
});
expect(divsCount).toBe(3);
@ -553,7 +553,7 @@ describe('querySelector', function () {
}
`
);
const sum = await page.$$eval('allArray/section', (sections) => {
const sum = await page.$$eval('allArray/section', sections => {
return sections.reduce((acc, section) => {
return acc + Number(section.textContent);
}, 0);

View File

@ -43,7 +43,7 @@ describe('request interception', function () {
const actionResults: ActionResult[] = [];
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.url().endsWith('.css')) {
request.continue(
{headers: {...request.headers(), xaction: 'continue'}},
@ -53,7 +53,7 @@ describe('request interception', function () {
request.continue({}, 0);
}
});
page.on('request', (request) => {
page.on('request', request => {
if (request.url().endsWith('.css')) {
request.respond(
{headers: {xaction: 'respond'}},
@ -63,20 +63,20 @@ describe('request interception', function () {
request.continue({}, 0);
}
});
page.on('request', (request) => {
page.on('request', request => {
if (request.url().endsWith('.css')) {
request.abort('aborted', expectedAction === 'abort' ? 1 : 0);
} else {
request.continue({}, 0);
}
});
page.on('response', (response) => {
page.on('response', response => {
const {xaction} = response!.headers();
if (response!.url().endsWith('.css') && !!xaction) {
actionResults.push(xaction as ActionResult);
}
});
page.on('requestfailed', (request) => {
page.on('requestfailed', request => {
if (request.url().endsWith('.css')) {
actionResults.push('abort');
}
@ -107,7 +107,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (utils.isFavicon(request)) {
request.continue({}, 0);
return;
@ -133,7 +133,7 @@ describe('request interception', function () {
server.setRedirect('/rredirect', '/empty.html');
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
await page.setContent(`
@ -142,7 +142,7 @@ describe('request interception', function () {
</form>
`);
await Promise.all([
page.$eval('form', (form) => {
page.$eval('form', form => {
return (form as HTMLFormElement).submit();
}),
page.waitForNavigation(),
@ -154,7 +154,7 @@ describe('request interception', function () {
server.setRedirect('/rrredirect', '/empty.html');
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const headers = Object.assign({}, request.headers(), {
foo: 'bar',
});
@ -170,7 +170,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const headers = Object.assign({}, request.headers(), {
foo: 'bar',
origin: undefined, // remove "origin" header
@ -190,7 +190,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
if (!utils.isFavicon(request)) {
requests.push(request);
}
@ -209,7 +209,7 @@ describe('request interception', function () {
// Setup request interception.
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
const response = await page.reload();
@ -219,7 +219,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.once('request', (request) => {
page.once('request', request => {
return request.continue({}, 0);
});
await page.goto(server.EMPTY_PAGE);
@ -233,7 +233,7 @@ describe('request interception', function () {
foo: 'bar',
});
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
expect(request.headers()['foo']).toBe('bar');
request.continue({}, 0);
});
@ -247,7 +247,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE);
server.setRedirect('/logo.png', '/pptr.png');
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
const status = await page.evaluate(async () => {
@ -263,7 +263,7 @@ describe('request interception', function () {
await page.setExtraHTTPHeaders({referer: server.EMPTY_PAGE});
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
expect(request.headers()['referer']).toBe(server.EMPTY_PAGE);
request.continue({}, 0);
});
@ -274,7 +274,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.url().endsWith('.css')) {
request.abort('failed', 0);
} else {
@ -294,11 +294,11 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.abort('failed', 0);
});
let abortReason = null;
page.on('request', (request) => {
page.on('request', request => {
abortReason = request.abortErrorReason();
request.continue({}, 0);
});
@ -309,11 +309,11 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.abort('internetdisconnected', 0);
});
let failedRequest!: HTTPRequest;
page.on('requestfailed', (request) => {
page.on('requestfailed', request => {
return (failedRequest = request);
});
await page.goto(server.EMPTY_PAGE).catch(() => {});
@ -329,7 +329,7 @@ describe('request interception', function () {
referer: 'http://google.com/',
});
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
const [request] = await Promise.all([
@ -342,11 +342,11 @@ describe('request interception', function () {
const {page, server, isChrome} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.abort('failed', 0);
});
let error!: Error;
await page.goto(server.EMPTY_PAGE).catch((error_) => {
await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -361,7 +361,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
request.continue({}, 0);
requests.push(request);
});
@ -401,7 +401,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
request.continue({}, 0);
if (!utils.isFavicon(request)) {
requests.push(request);
@ -432,7 +432,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
server.setRedirect('/non-existing.json', '/non-existing-2.json');
server.setRedirect('/non-existing-2.json', '/simple.html');
page.on('request', (request) => {
page.on('request', request => {
if (request.url().includes('non-existing-2')) {
request.abort('failed', 0);
} else {
@ -465,7 +465,7 @@ describe('request interception', function () {
let spinner = false;
// Cancel 2nd request.
page.on('request', (request) => {
page.on('request', request => {
if (utils.isFavicon(request)) {
request.continue({}, 0);
return;
@ -476,21 +476,21 @@ describe('request interception', function () {
const results = await page.evaluate(() => {
return Promise.all([
fetch('/zzz')
.then((response) => {
.then(response => {
return response!.text();
})
.catch(() => {
return 'FAILED';
}),
fetch('/zzz')
.then((response) => {
.then(response => {
return response!.text();
})
.catch(() => {
return 'FAILED';
}),
fetch('/zzz')
.then((response) => {
.then(response => {
return response!.text();
})
.catch(() => {
@ -505,7 +505,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
requests.push(request);
request.continue({}, 0);
});
@ -521,13 +521,13 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
!utils.isFavicon(request) && requests.push(request);
request.continue({}, 0);
});
const dataURL = 'data:text/html,<div>yo</div>';
const text = await page.evaluate((url: string) => {
return fetch(url).then((r) => {
return fetch(url).then(r => {
return r.text();
});
}, dataURL);
@ -540,7 +540,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
requests.push(request);
request.continue({}, 0);
});
@ -556,7 +556,7 @@ describe('request interception', function () {
// The requestWillBeSent will report encoded URL, whereas interception will
// report URL as-is. @see crbug.com/759388
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
const response = await page.goto(
@ -571,7 +571,7 @@ describe('request interception', function () {
server.setRoute('/malformed?rnd=%911', (_req, res) => {
return res.end();
});
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
const response = await page.goto(server.PREFIX + '/malformed?rnd=%911');
@ -584,7 +584,7 @@ describe('request interception', function () {
// report encoded URL for stylesheet. @see crbug.com/759388
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
request.continue({}, 0);
requests.push(request);
});
@ -601,7 +601,7 @@ describe('request interception', function () {
await page.setContent('<iframe></iframe>');
await page.setRequestInterception(true);
let request!: HTTPRequest;
page.on('request', async (r) => {
page.on('request', async r => {
return (request = r);
});
page.$eval(
@ -614,11 +614,11 @@ describe('request interception', function () {
// Wait for request interception.
await utils.waitEvent(page, 'request');
// Delete frame to cause request to be canceled.
await page.$eval('iframe', (frame) => {
await page.$eval('iframe', frame => {
return frame.remove();
});
let error!: Error;
await request.continue({}, 0).catch((error_) => {
await request.continue({}, 0).catch(error_ => {
return (error = error_);
});
expect(error).toBeUndefined();
@ -627,7 +627,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
let error!: Error;
page.on('request', async (request) => {
page.on('request', async request => {
try {
await request.continue({}, 0);
} catch (error_) {
@ -642,7 +642,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const urls = new Set();
page.on('request', (request) => {
page.on('request', request => {
urls.add(request.url().split('/').pop());
request.continue({}, 0);
});
@ -661,12 +661,12 @@ describe('request interception', function () {
await page.setRequestInterception(true);
await page.setCacheEnabled(false);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
const cached = [];
page.on('requestservedfromcache', (r) => {
page.on('requestservedfromcache', r => {
return cached.push(r);
});
@ -681,12 +681,12 @@ describe('request interception', function () {
await page.setRequestInterception(true);
await page.setCacheEnabled(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
const cached = [];
page.on('requestservedfromcache', (r) => {
page.on('requestservedfromcache', r => {
return cached.push(r);
});
@ -698,12 +698,12 @@ describe('request interception', function () {
await page.setRequestInterception(true);
await page.setCacheEnabled(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
await page.goto(server.PREFIX + '/cached/one-style-font.html');
await page.waitForResponse((r) => {
await page.waitForResponse(r => {
return r.url().endsWith('/one-style.woff');
});
});
@ -714,7 +714,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue({}, 0);
});
await page.goto(server.EMPTY_PAGE);
@ -723,7 +723,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const headers = Object.assign({}, request.headers());
headers['FOO'] = 'bar';
request.continue({headers}, 0);
@ -741,14 +741,14 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const redirectURL = request.url().includes('/empty.html')
? server.PREFIX + '/consolelog.html'
: undefined;
request.continue({url: redirectURL}, 0);
});
let consoleMessage!: ConsoleMessage;
page.on('console', (msg) => {
page.on('console', msg => {
return (consoleMessage = msg);
});
await page.goto(server.EMPTY_PAGE);
@ -761,7 +761,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.continue({method: 'POST'}, 0);
});
const [request] = await Promise.all([
@ -778,7 +778,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.continue({postData: 'doggo'}, 0);
});
const [serverRequest] = await Promise.all([
@ -793,7 +793,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.continue({method: 'POST', postData: 'doggo'}, 0);
});
const [serverRequest] = await Promise.all([
@ -810,7 +810,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.respond(
{
status: 201,
@ -835,7 +835,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.respond(
{
status: 200,
@ -845,7 +845,7 @@ describe('request interception', function () {
);
});
let response = null;
page.on('request', (request) => {
page.on('request', request => {
response = request.responseForRequest();
request.continue({}, 0);
});
@ -856,7 +856,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.respond(
{
status: 422,
@ -878,7 +878,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (!request.url().includes('rrredirect')) {
request.continue({}, 0);
return;
@ -904,7 +904,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const imageBuffer = fs.readFileSync(
path.join(__dirname, '../assets', 'pptr.png')
);
@ -916,11 +916,11 @@ describe('request interception', function () {
0
);
});
await page.evaluate((PREFIX) => {
await page.evaluate(PREFIX => {
const img = document.createElement('img');
img.src = PREFIX + '/does-not-exist.png';
document.body.appendChild(img);
return new Promise((fulfill) => {
return new Promise(fulfill => {
return (img.onload = fulfill);
});
}, server.PREFIX);
@ -931,7 +931,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.respond(
{
status: 200,
@ -957,13 +957,13 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.continue();
});
page.on('request', (request) => {
page.on('request', request => {
expect(request.isInterceptResolutionHandled()).toBeTruthy();
});
page.on('request', (request) => {
page.on('request', request => {
const {action} = request.interceptResolutionState();
expect(action).toBe(InterceptResolutionAction.AlreadyHandled);
});

View File

@ -35,7 +35,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (utils.isFavicon(request)) {
request.continue();
return;
@ -62,7 +62,7 @@ describe('request interception', function () {
server.setRedirect('/rredirect', '/empty.html');
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
await page.setContent(`
@ -71,7 +71,7 @@ describe('request interception', function () {
</form>
`);
await Promise.all([
page.$eval('form', (form) => {
page.$eval('form', form => {
return (form as HTMLFormElement).submit();
}),
page.waitForNavigation(),
@ -83,7 +83,7 @@ describe('request interception', function () {
server.setRedirect('/rrredirect', '/empty.html');
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const headers = Object.assign({}, request.headers(), {
foo: 'bar',
});
@ -96,7 +96,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const headers = Object.assign({}, request.headers(), {
foo: 'bar',
origin: undefined, // remove "origin" header
@ -116,7 +116,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
if (!utils.isFavicon(request)) {
requests.push(request);
}
@ -135,7 +135,7 @@ describe('request interception', function () {
// Setup request interception.
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
const response = (await page.reload())!;
@ -145,7 +145,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.once('request', (request) => {
page.once('request', request => {
return request.continue();
});
await page.goto(server.EMPTY_PAGE);
@ -159,7 +159,7 @@ describe('request interception', function () {
foo: 'bar',
});
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
expect(request.headers()['foo']).toBe('bar');
request.continue();
});
@ -173,7 +173,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE);
server.setRedirect('/logo.png', '/pptr.png');
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
const status = await page.evaluate(async () => {
@ -189,7 +189,7 @@ describe('request interception', function () {
await page.setExtraHTTPHeaders({referer: server.EMPTY_PAGE});
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
expect(request.headers()['referer']).toBe(server.EMPTY_PAGE);
request.continue();
});
@ -200,7 +200,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (request.url().endsWith('.css')) {
request.abort();
} else {
@ -220,11 +220,11 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.abort('internetdisconnected');
});
let failedRequest!: HTTPRequest;
page.on('requestfailed', (request) => {
page.on('requestfailed', request => {
return (failedRequest = request);
});
await page.goto(server.EMPTY_PAGE).catch(() => {});
@ -240,7 +240,7 @@ describe('request interception', function () {
referer: 'http://google.com/',
});
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
const [request] = await Promise.all([
@ -253,11 +253,11 @@ describe('request interception', function () {
const {page, server, isChrome} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.abort();
});
let error!: Error;
await page.goto(server.EMPTY_PAGE).catch((error_) => {
await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -272,7 +272,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
request.continue();
requests.push(request);
});
@ -312,7 +312,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
request.continue();
if (!utils.isFavicon(request)) {
requests.push(request);
@ -343,7 +343,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
server.setRedirect('/non-existing.json', '/non-existing-2.json');
server.setRedirect('/non-existing-2.json', '/simple.html');
page.on('request', (request) => {
page.on('request', request => {
if (request.url().includes('non-existing-2')) {
request.abort();
} else {
@ -376,7 +376,7 @@ describe('request interception', function () {
let spinner = false;
// Cancel 2nd request.
page.on('request', (request) => {
page.on('request', request => {
if (utils.isFavicon(request)) {
request.continue();
return;
@ -387,21 +387,21 @@ describe('request interception', function () {
const results = await page.evaluate(() => {
return Promise.all([
fetch('/zzz')
.then((response) => {
.then(response => {
return response.text();
})
.catch(() => {
return 'FAILED';
}),
fetch('/zzz')
.then((response) => {
.then(response => {
return response.text();
})
.catch(() => {
return 'FAILED';
}),
fetch('/zzz')
.then((response) => {
.then(response => {
return response.text();
})
.catch(() => {
@ -416,7 +416,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
requests.push(request);
request.continue();
});
@ -432,13 +432,13 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
!utils.isFavicon(request) && requests.push(request);
request.continue();
});
const dataURL = 'data:text/html,<div>yo</div>';
const text = await page.evaluate((url: string) => {
return fetch(url).then((r) => {
return fetch(url).then(r => {
return r.text();
});
}, dataURL);
@ -451,7 +451,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
requests.push(request);
request.continue();
});
@ -467,7 +467,7 @@ describe('request interception', function () {
// The requestWillBeSent will report encoded URL, whereas interception will
// report URL as-is. @see crbug.com/759388
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
const response = (await page.goto(
@ -482,7 +482,7 @@ describe('request interception', function () {
server.setRoute('/malformed?rnd=%911', (_req, res) => {
return res.end();
});
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
const response = (await page.goto(
@ -497,7 +497,7 @@ describe('request interception', function () {
// report encoded URL for stylesheet. @see crbug.com/759388
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', (request) => {
page.on('request', request => {
request.continue();
requests.push(request);
});
@ -514,7 +514,7 @@ describe('request interception', function () {
await page.setContent('<iframe></iframe>');
await page.setRequestInterception(true);
let request!: HTTPRequest;
page.on('request', async (r) => {
page.on('request', async r => {
return (request = r);
});
page.$eval(
@ -527,11 +527,11 @@ describe('request interception', function () {
// Wait for request interception.
await utils.waitEvent(page, 'request');
// Delete frame to cause request to be canceled.
await page.$eval('iframe', (frame) => {
await page.$eval('iframe', frame => {
return frame.remove();
});
let error!: Error;
await request.continue().catch((error_) => {
await request.continue().catch(error_ => {
return (error = error_);
});
expect(error).toBeUndefined();
@ -540,7 +540,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
let error!: Error;
page.on('request', async (request) => {
page.on('request', async request => {
try {
await request.continue();
} catch (error_) {
@ -555,7 +555,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const urls = new Set();
page.on('request', (request) => {
page.on('request', request => {
urls.add(request.url().split('/').pop());
request.continue();
});
@ -574,12 +574,12 @@ describe('request interception', function () {
await page.setRequestInterception(true);
await page.setCacheEnabled(false);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
const cached = [];
page.on('requestservedfromcache', (r) => {
page.on('requestservedfromcache', r => {
return cached.push(r);
});
@ -594,12 +594,12 @@ describe('request interception', function () {
await page.setRequestInterception(true);
await page.setCacheEnabled(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
const cached = [];
page.on('requestservedfromcache', (r) => {
page.on('requestservedfromcache', r => {
return cached.push(r);
});
@ -611,12 +611,12 @@ describe('request interception', function () {
await page.setRequestInterception(true);
await page.setCacheEnabled(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
await page.goto(server.PREFIX + '/cached/one-style-font.html');
await page.waitForResponse((r) => {
await page.waitForResponse(r => {
return r.url().endsWith('/one-style.woff');
});
});
@ -627,7 +627,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
return request.continue();
});
await page.goto(server.EMPTY_PAGE);
@ -636,7 +636,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const headers = Object.assign({}, request.headers());
headers['FOO'] = 'bar';
request.continue({headers});
@ -654,14 +654,14 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const redirectURL = request.url().includes('/empty.html')
? server.PREFIX + '/consolelog.html'
: undefined;
request.continue({url: redirectURL});
});
let consoleMessage!: ConsoleMessage;
page.on('console', (msg) => {
page.on('console', msg => {
return (consoleMessage = msg);
});
await page.goto(server.EMPTY_PAGE);
@ -674,7 +674,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.continue({method: 'POST'});
});
const [request] = await Promise.all([
@ -691,7 +691,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.continue({postData: 'doggo'});
});
const [serverRequest] = await Promise.all([
@ -706,7 +706,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.continue({method: 'POST', postData: 'doggo'});
});
const [serverRequest] = await Promise.all([
@ -721,14 +721,14 @@ describe('request interception', function () {
let error!: Error;
await page.setRequestInterception(true);
page.on('request', async (request) => {
page.on('request', async request => {
await request
.continue({
headers: {
'X-Invalid-Header': 'a\nb',
},
})
.catch((error_) => {
.catch(error_ => {
error = error_ as Error;
});
await request.continue();
@ -743,7 +743,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.respond({
status: 201,
headers: {
@ -765,7 +765,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.respond({
status: 422,
body: 'Yo, page!',
@ -784,7 +784,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
if (!request.url().includes('rrredirect')) {
request.continue();
return;
@ -807,7 +807,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.respond({
status: 200,
headers: {
@ -820,10 +820,10 @@ describe('request interception', function () {
});
const response = (await page.goto(server.EMPTY_PAGE))!;
const cookies = await page.cookies();
const firstCookie = cookies.find((cookie) => {
const firstCookie = cookies.find(cookie => {
return cookie.name === 'first';
});
const secondCookie = cookies.find((cookie) => {
const secondCookie = cookies.find(cookie => {
return cookie.name === 'second';
});
expect(response.status()).toBe(200);
@ -838,7 +838,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
const imageBuffer = fs.readFileSync(
path.join(__dirname, '../assets', 'pptr.png')
);
@ -847,11 +847,11 @@ describe('request interception', function () {
body: imageBuffer,
});
});
await page.evaluate((PREFIX) => {
await page.evaluate(PREFIX => {
const img = document.createElement('img');
img.src = PREFIX + '/does-not-exist.png';
document.body.appendChild(img);
return new Promise((fulfill) => {
return new Promise(fulfill => {
return (img.onload = fulfill);
});
}, server.PREFIX);
@ -862,7 +862,7 @@ describe('request interception', function () {
const {page, server} = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
page.on('request', request => {
request.respond({
status: 200,
headers: {
@ -886,14 +886,14 @@ describe('request interception', function () {
let error!: Error;
await page.setRequestInterception(true);
page.on('request', async (request) => {
page.on('request', async request => {
await request
.respond({
headers: {
'X-Invalid-Header': 'a\nb',
},
})
.catch((error_) => {
.catch(error_ => {
error = error_ as Error;
});
await request.respond({

View File

@ -124,7 +124,7 @@ describe('Screenshots', function () {
expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`);
}
await Promise.all(
pages.map((page) => {
pages.map(page => {
return page.close();
})
);
@ -310,9 +310,7 @@ describe('Screenshots', function () {
await page.evaluate((element: HTMLElement) => {
return element.remove();
}, elementHandle);
const screenshotError = await elementHandle
.screenshot()
.catch((error) => {
const screenshotError = await elementHandle.screenshot().catch(error => {
return error;
});
expect(screenshotError.message).toBe(
@ -324,7 +322,7 @@ describe('Screenshots', function () {
await page.setContent('<div style="width: 50px; height: 0"></div>');
const div = (await page.$('div'))!;
const error = await div.screenshot().catch((error_) => {
const error = await div.screenshot().catch(error_ => {
return error_;
});
expect(error.message).toBe('Node has 0 height.');

View File

@ -37,12 +37,12 @@ describe('Target', function () {
// The pages will be the testing page and the original newtab page
const targets = browser.targets();
expect(
targets.some((target) => {
targets.some(target => {
return target.type() === 'page' && target.url() === 'about:blank';
})
).toBeTruthy();
expect(
targets.some((target) => {
targets.some(target => {
return target.type() === 'browser';
})
).toBeTruthy();
@ -59,7 +59,7 @@ describe('Target', function () {
const {browser} = getTestState();
const targets = browser.targets();
const browserTarget = targets.find((target) => {
const browserTarget = targets.find(target => {
return target.type() === 'browser';
});
expect(browserTarget).toBeTruthy();
@ -69,7 +69,7 @@ describe('Target', function () {
// The pages will be the testing page and the original newtab page
const allPages = await browser.pages();
const originalPage = allPages.find((p) => {
const originalPage = allPages.find(p => {
return p !== page;
})!;
expect(
@ -84,12 +84,12 @@ describe('Target', function () {
const [otherPage] = await Promise.all([
context
.waitForTarget((target) => {
return target.page().then((page) => {
.waitForTarget(target => {
return target.page().then(page => {
return page!.url() === server.CROSS_PROCESS_PREFIX + '/empty.html';
});
})
.then((target) => {
.then(target => {
return target.page();
}),
page.evaluate((url: string) => {
@ -108,10 +108,10 @@ describe('Target', function () {
const [otherPage] = await Promise.all([
context
.waitForTarget((target) => {
.waitForTarget(target => {
return target.url() === server.CROSS_PROCESS_PREFIX + '/empty.html';
})
.then((target) => {
.then(target => {
return target.page();
}),
page.evaluate((url: string) => {
@ -130,8 +130,8 @@ describe('Target', function () {
expect(allPages).toContain(page);
expect(allPages).toContain(otherPage);
const closePagePromise = new Promise((fulfill) => {
return context.once('targetdestroyed', (target) => {
const closePagePromise = new Promise(fulfill => {
return context.once('targetdestroyed', target => {
return fulfill(target.page());
});
});
@ -139,7 +139,7 @@ describe('Target', function () {
expect(await closePagePromise).toBe(otherPage);
allPages = (await Promise.all(
context.targets().map((target) => {
context.targets().map(target => {
return target.page();
})
)) as Page[];
@ -153,8 +153,8 @@ describe('Target', function () {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
const createdTarget = new Promise<Target>((fulfill) => {
return context.once('targetcreated', (target) => {
const createdTarget = new Promise<Target>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target);
});
});
@ -166,8 +166,8 @@ describe('Target', function () {
server.PREFIX + '/serviceworkers/empty/sw.js'
);
const destroyedTarget = new Promise((fulfill) => {
return context.once('targetdestroyed', (target) => {
const destroyedTarget = new Promise(fulfill => {
return context.once('targetdestroyed', target => {
return fulfill(target);
});
});
@ -186,7 +186,7 @@ describe('Target', function () {
await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html');
const target = await context.waitForTarget((target) => {
const target = await context.waitForTarget(target => {
return target.type() === 'service_worker';
});
const worker = (await target.worker())!;
@ -203,7 +203,7 @@ describe('Target', function () {
await page.evaluate(() => {
new SharedWorker('data:text/javascript,console.log("hi")');
});
const target = await context.waitForTarget((target) => {
const target = await context.waitForTarget(target => {
return target.type() === 'shared_worker';
});
const worker = (await target.worker())!;
@ -217,16 +217,16 @@ describe('Target', function () {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
let changedTarget = new Promise<Target>((fulfill) => {
return context.once('targetchanged', (target) => {
let changedTarget = new Promise<Target>(fulfill => {
return context.once('targetchanged', target => {
return fulfill(target);
});
});
await page.goto(server.CROSS_PROCESS_PREFIX + '/');
expect((await changedTarget).url()).toBe(server.CROSS_PROCESS_PREFIX + '/');
changedTarget = new Promise((fulfill) => {
return context.once('targetchanged', (target) => {
changedTarget = new Promise(fulfill => {
return context.once('targetchanged', target => {
return fulfill(target);
});
});
@ -241,8 +241,8 @@ describe('Target', function () {
return (targetChanged = true);
};
context.on('targetchanged', listener);
const targetPromise = new Promise<Target>((fulfill) => {
return context.once('targetcreated', (target) => {
const targetPromise = new Promise<Target>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target);
});
});
@ -251,8 +251,8 @@ describe('Target', function () {
expect(target.url()).toBe('about:blank');
const newPage = await newPagePromise;
const targetPromise2 = new Promise<Target>((fulfill) => {
return context.once('targetcreated', (target) => {
const targetPromise2 = new Promise<Target>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target);
});
});
@ -283,7 +283,7 @@ describe('Target', function () {
server.waitForRequest('/one-style.css'),
]);
// Connect to the opened page.
const target = await context.waitForTarget((target) => {
const target = await context.waitForTarget(target => {
return target.url().includes('one-style.html');
});
const newPage = (await target.page())!;
@ -301,8 +301,8 @@ describe('Target', function () {
await page.goto(server.EMPTY_PAGE);
const [createdTarget] = await Promise.all([
new Promise<Target>((fulfill) => {
return context.once('targetcreated', (target) => {
new Promise<Target>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target);
});
}),
@ -320,14 +320,14 @@ describe('Target', function () {
const {browser, puppeteer, server} = getTestState();
let resolved = false;
const targetPromise = browser.waitForTarget((target) => {
const targetPromise = browser.waitForTarget(target => {
return target.url() === server.EMPTY_PAGE;
});
targetPromise
.then(() => {
return (resolved = true);
})
.catch((error) => {
.catch(error => {
resolved = true;
if (error instanceof puppeteer.errors.TimeoutError) {
console.error(error);
@ -356,14 +356,14 @@ describe('Target', function () {
let error!: Error;
await browser
.waitForTarget(
(target) => {
target => {
return target.url() === server.EMPTY_PAGE;
},
{
timeout: 1,
}
)
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);

View File

@ -93,7 +93,7 @@ describeChromeOnly('Tracing', function () {
await page.tracing.start({path: outputFile});
const newPage = await browser.newPage();
let error!: Error;
await newPage.tracing.start({ path: outputFile }).catch((error_) => {
await newPage.tracing.start({path: outputFile}).catch(error_ => {
return (error = error_);
});
await newPage.close();

View File

@ -72,16 +72,14 @@ export const attachFrame = async (
frame.src = url;
frame.id = frameId;
document.body.appendChild(frame);
await new Promise((x) => {
await new Promise(x => {
return (frame.onload = x);
});
return frame;
}
};
export const isFavicon = (request: {
url: () => string | string[];
}): boolean => {
export const isFavicon = (request: {url: () => string | string[]}): boolean => {
return request.url().includes('favicon.ico');
};
@ -107,7 +105,7 @@ export async function navigateFrame(
function navigateFrame(frameId: string, url: any) {
const frame = document.getElementById(frameId) as HTMLIFrameElement;
frame.src = url;
return new Promise((x) => {
return new Promise(x => {
return (frame.onload = x);
});
}
@ -136,7 +134,7 @@ export const waitEvent = (
return true;
}
): Promise<any> => {
return new Promise((fulfill) => {
return new Promise(fulfill => {
emitter.on(eventName, function listener(event: any) {
if (!predicate(event)) {
return;

View File

@ -82,7 +82,7 @@ describe('waittask specs', function () {
await page.setContent(`<div>some text</div>`);
let error!: Error;
await page.waitFor('/html/body/div').catch((error_) => {
await page.waitFor('/html/body/div').catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -321,7 +321,7 @@ describe('waittask specs', function () {
polling: 'raf',
}
)
.catch((error_) => {
.catch(error_ => {
return (error = error_);
}),
page.evaluate(() => {
@ -417,7 +417,7 @@ describe('waittask specs', function () {
const {page, puppeteer} = getTestState();
let error!: Error;
await page.waitForFunction('false', { timeout: 10 }).catch((error_) => {
await page.waitForFunction('false', {timeout: 10}).catch(error_ => {
return (error = error_);
});
@ -429,7 +429,7 @@ describe('waittask specs', function () {
page.setDefaultTimeout(1);
let error!: Error;
await page.waitForFunction('false').catch((error_) => {
await page.waitForFunction('false').catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -618,7 +618,7 @@ describe('waittask specs', function () {
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1]!;
let waitError: Error | undefined;
const waitPromise = frame.waitForSelector('.box').catch((error) => {
const waitPromise = frame.waitForSelector('.box').catch(error => {
return (waitError = error);
});
await detachFrame(page, 'frame1');
@ -763,7 +763,7 @@ describe('waittask specs', function () {
const {page, puppeteer} = getTestState();
let error!: Error;
await page.waitForSelector('div', { timeout: 10 }).catch((error_) => {
await page.waitForSelector('div', {timeout: 10}).catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -778,7 +778,7 @@ describe('waittask specs', function () {
let error!: Error;
await page
.waitForSelector('div', {hidden: true, timeout: 10})
.catch((error_) => {
.catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
@ -816,7 +816,7 @@ describe('waittask specs', function () {
const {page} = getTestState();
let error!: Error;
await page.waitForSelector('.zombo', { timeout: 10 }).catch((error_) => {
await page.waitForSelector('.zombo', {timeout: 10}).catch(error_ => {
return (error = error_);
});
expect(error?.stack).toContain('waiting for selector `.zombo` failed');
@ -847,7 +847,7 @@ describe('waittask specs', function () {
const {page, puppeteer} = getTestState();
let error!: Error;
await page.waitForXPath('//div', { timeout: 10 }).catch((error_) => {
await page.waitForXPath('//div', {timeout: 10}).catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -876,7 +876,7 @@ describe('waittask specs', function () {
let waitError: Error | undefined;
const waitPromise = frame
.waitForXPath('//*[@class="box"]')
.catch((error) => {
.catch(error => {
return (waitError = error);
});
await detachFrame(page, 'frame1');

View File

@ -32,7 +32,7 @@ describeFailsFirefox('Workers', function () {
const {page, server} = getTestState();
await Promise.all([
new Promise((x) => {
new Promise(x => {
return page.once('workercreated', x);
}),
page.goto(server.PREFIX + '/worker/worker.html'),
@ -52,7 +52,7 @@ describeFailsFirefox('Workers', function () {
it('should emit created and destroyed events', async () => {
const {page} = getTestState();
const workerCreatedPromise = new Promise<WebWorker>((x) => {
const workerCreatedPromise = new Promise<WebWorker>(x => {
return page.once('workercreated', x);
});
const workerObj = await page.evaluateHandle(() => {
@ -62,14 +62,14 @@ describeFailsFirefox('Workers', function () {
const workerThisObj = await worker.evaluateHandle(() => {
return this;
});
const workerDestroyedPromise = new Promise((x) => {
const workerDestroyedPromise = new Promise(x => {
return page.once('workerdestroyed', x);
});
await page.evaluate((workerObj: Worker) => {
return workerObj.terminate();
}, workerObj);
expect(await workerDestroyedPromise).toBe(worker);
const error = await workerThisObj.getProperty('self').catch((error) => {
const error = await workerThisObj.getProperty('self').catch(error => {
return error;
});
expect(error.message).toContain('Most likely the worker has been closed.');
@ -93,7 +93,7 @@ describeFailsFirefox('Workers', function () {
it('should have JSHandles for console logs', async () => {
const {page} = getTestState();
const logPromise = new Promise<ConsoleMessage>((x) => {
const logPromise = new Promise<ConsoleMessage>(x => {
return page.on('console', x);
});
await page.evaluate(() => {
@ -109,7 +109,7 @@ describeFailsFirefox('Workers', function () {
it('should have an execution context', async () => {
const {page} = getTestState();
const workerCreatedPromise = new Promise<WebWorker>((x) => {
const workerCreatedPromise = new Promise<WebWorker>(x => {
return page.once('workercreated', x);
});
await page.evaluate(() => {
@ -121,7 +121,7 @@ describeFailsFirefox('Workers', function () {
it('should report errors', async () => {
const {page} = getTestState();
const errorPromise = new Promise<Error>((x) => {
const errorPromise = new Promise<Error>(x => {
return page.on('pageerror', x);
});
await page.evaluate(() => {

View File

@ -22,7 +22,7 @@ const { promisify } = require('util');
const exec = promisify(child_process.exec);
const fsAccess = promisify(fs.access);
const fileExists = async (filePath) => {
const fileExists = async filePath => {
return fsAccess(filePath)
.then(() => {
return true;
@ -45,7 +45,7 @@ const fileExists = async (filePath) => {
* place.
*/
async function compileTypeScript() {
return exec('npm run build:tsc').catch((error) => {
return exec('npm run build:tsc').catch(error => {
console.error('Error running TypeScript', error);
process.exit(1);
});

View File

@ -168,10 +168,10 @@ function runScript(scriptPath, revisionInfo) {
},
});
return new Promise((resolve, reject) => {
child.on('error', (err) => {
child.on('error', err => {
return reject(err);
});
child.on('exit', (code) => {
child.on('exit', code => {
return resolve(code);
});
});
@ -189,10 +189,10 @@ function runUnitTest(pattern, revisionInfo) {
},
});
return new Promise((resolve, reject) => {
child.on('error', (err) => {
child.on('error', err => {
return reject(err);
});
child.on('exit', (code) => {
child.on('exit', code => {
return resolve(code);
});
});
@ -282,14 +282,14 @@ function fetchJSON(url) {
const req = agent.request(options, function (res) {
let result = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
res.on('data', chunk => {
return (result += chunk);
});
res.on('end', () => {
return resolve(JSON.parse(result));
});
});
req.on('error', (err) => {
req.on('error', err => {
return reject(err);
});
req.end();

View File

@ -155,7 +155,7 @@ async function checkOmahaProxyAvailability() {
'https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/LAST_CHANGE'
),
])
).map((s) => {
).map(s => {
return parseInt(s, 10);
});
const from = Math.max(...latestRevisions);
@ -185,7 +185,7 @@ async function printLatestRevisionForPlatform(platform) {
'https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/LAST_CHANGE'
),
])
).map((s) => {
).map(s => {
return parseInt(s, 10);
});
const from = Math.max(...latestRevisions);
@ -246,7 +246,7 @@ async function checkRangeAvailability({
table.drawRow([''].concat(platforms));
}
const fetchers = platforms.map((platform) => {
const fetchers = platforms.map(platform => {
return new BrowserFetcher('', {platform});
});
@ -257,11 +257,11 @@ async function checkRangeAvailability({
revision !== revisionToStop;
revision += inc
) {
const promises = fetchers.map((fetcher) => {
const promises = fetchers.map(fetcher => {
return fetcher.canDownload(revision);
});
const availability = await Promise.all(promises);
const allAvailable = availability.every((e) => {
const allAvailable = availability.every(e => {
return !!e;
});
if (table) {
@ -292,11 +292,11 @@ async function checkRangeAvailability({
*/
function fetch(url) {
let resolve;
const promise = new Promise((x) => {
const promise = new Promise(x => {
return (resolve = x);
});
https
.get(url, (response) => {
.get(url, response => {
if (response.statusCode !== 200) {
resolve(null);
return;

View File

@ -86,10 +86,10 @@ async function main(url) {
return;
}
const devicePayloads = json.extensions
.filter((extension) => {
.filter(extension => {
return extension.type === 'emulated-device';
})
.map((extension) => {
.map(extension => {
return extension.device;
});
let devices = [];
@ -116,7 +116,7 @@ async function main(url) {
}
}
}
devices = devices.filter((device) => {
devices = devices.filter(device => {
return device.viewport.isMobile;
});
devices.sort((a, b) => {
@ -287,10 +287,10 @@ function httpGET(url) {
const driver = url.startsWith('https://')
? require('https')
: require('http');
const request = driver.get(url, (response) => {
const request = driver.get(url, response => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
response.on('data', chunk => {
return (data += chunk);
});
response.on('end', () => {

View File

@ -67,7 +67,7 @@ export class TestServer {
static async create(dirPath: string, port: number): Promise<TestServer> {
const server = new TestServer(dirPath, port);
await new Promise((x) => {
await new Promise(x => {
return server.#server.once('listening', x);
});
return server;
@ -79,7 +79,7 @@ export class TestServer {
cert: readFileSync(join(__dirname, '..', 'cert.pem')),
passphrase: 'aaaa',
});
await new Promise((x) => {
await new Promise(x => {
return server.#server.once('listening', x);
});
return server;
@ -103,7 +103,7 @@ export class TestServer {
this.#connections.add(connection);
// ECONNRESET is a legit error given
// that tab closing simply kills process.
connection.on('error', (error) => {
connection.on('error', error => {
if ((error as NodeJS.ErrnoException).code !== 'ECONNRESET') {
throw error;
}
@ -135,7 +135,7 @@ export class TestServer {
socket.destroy();
}
this.#connections.clear();
await new Promise((x) => {
await new Promise(x => {
return this.#server.close(x);
});
}
@ -192,7 +192,7 @@ export class TestServer {
throw error;
}
});
request.postBody = new Promise((resolve) => {
request.postBody = new Promise(resolve => {
let body = '';
request.on('data', (chunk: string) => {
return (body += chunk);