fix: much better TypeScript definitions (#6837)
This PR aims to vastly improve our TS types and how we ship them. Our previous attempt at shipping TypeScript was unfortunately flawed for many reasons when compared to the @types/puppeteer package: * It only worked if you needed the default export. If you wanted to import a type that Puppeteer uses, you'd have to do `import type X from 'puppeteer/lib/...'`. This is not something we want to encourage because that means our internal file structure becomes almost public API. * It gave absolutely no help to CommonJS users in JS files because it would warn people they needed to do `const pptr = require('puppeteer').default, which is not correct. * I found a bug in the `evaluate` types which mean't you couldn't override the types to provide more info, and TS would insist the types were all `unknown`. The goal of this PR is to support: 1. In a `ts` file, `import puppeteer from 'puppeteer'` 1. In a `ts` file, `import type {ElementHandle} from 'puppeteer'` 1. In a `ts` file, referencing a type as `puppeteer.ElementHandle` 1. In a `ts` file, you can get good type inference when running `foo.evaluate(x => x.clientHeight)`. 1. In a `js` file using CJS, you can do `const puppeteer = require('puppeteer')` and get good type help from VSCode. To test this I created a new empty repository with two test files in, one `.ts` file with this in: https://gist.github.com/jackfranklin/22ba2f390f97c7312cd70025a2096fc8, and a `js` file with this in: https://gist.github.com/jackfranklin/06bed136fdb22419cb7a8a9a4d4ef32f. These files included enough code to check that the types were behaving as I expected. The fix for our types was to make use of API Extractor, which we already use for our docs, to "rollup" all the disparate type files that TS generates into one large `types.d.ts` which contains all the various types that we define, such as: ```ts export declare class ElementHandle {...} export type EvaluateFn ... ``` If we then update our `package.json` `types` field to point to that file in `lib/types.d.ts`, this then allows a developer to write: ``` import type {ElementHandle} from 'puppeteer' ``` And get the correct type definitions. However, what the `types.d.ts` file doesn't do out of the box is declare the default export, so importing Puppeteer's default export to call a method such as `launch` on it will get you an error. That's where the `script/add-default-export-to-types.ts` comes in. It appends the following to the auto-generated `types.d.ts` file: ```ts declare const puppeteer: PuppeteerNode; export = puppeteer; ``` This tells TypeScript what the default export is, and by using the `export =` syntax, we make sure TS understands both in a TS ESM environment and in a JS CJS environment. Now the `build` step, which is run by GitHub Actions when we release, will generate the `.d.ts` file and then extend it with the default export code. To ensure that I was generating a valid package, I created a new repository locally with the two code samples linked in Gists above. I then ran: ``` npm init -y npm install --save-dev typescript npx tsc --init ``` Which gives me a base to test from. In Puppeteer, I ran `npm pack`, which packs the module into a tar that's almost identical to what would be published, so I can be confident that the .d.ts files in there are what would be published. I then installed it: ``` npm install --save-dev ../../puppeteer/puppeteer-7.0.1-post.tgz ``` And then reloaded VSCode in my dummy project. By deliberately making typos and hovering over the code, I could confirm that all the goals listed above were met, and this seems like a vast improvement on our types.
This commit is contained in:
parent
4e8d074c2f
commit
f1b46ab5fa
122
README.md
122
README.md
@ -1,7 +1,9 @@
|
|||||||
# Puppeteer
|
# Puppeteer
|
||||||
|
|
||||||
<!-- [START badges] -->
|
<!-- [START badges] -->
|
||||||
|
|
||||||
[![Build status](https://github.com/puppeteer/puppeteer/workflows/run-checks/badge.svg)](https://github.com/puppeteer/puppeteer/actions?query=workflow%3Arun-checks) [![npm puppeteer package](https://img.shields.io/npm/v/puppeteer.svg)](https://npmjs.org/package/puppeteer)
|
[![Build status](https://github.com/puppeteer/puppeteer/workflows/run-checks/badge.svg)](https://github.com/puppeteer/puppeteer/actions?query=workflow%3Arun-checks) [![npm puppeteer package](https://img.shields.io/npm/v/puppeteer.svg)](https://npmjs.org/package/puppeteer)
|
||||||
|
|
||||||
<!-- [END badges] -->
|
<!-- [END badges] -->
|
||||||
|
|
||||||
<img src="https://user-images.githubusercontent.com/10379601/29446482-04f7036a-841f-11e7-9872-91d1fc2ea683.png" height="200" align="right">
|
<img src="https://user-images.githubusercontent.com/10379601/29446482-04f7036a-841f-11e7-9872-91d1fc2ea683.png" height="200" align="right">
|
||||||
@ -11,21 +13,23 @@
|
|||||||
> Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). Puppeteer runs [headless](https://developers.google.com/web/updates/2017/04/headless-chrome) by default, but can be configured to run full (non-headless) Chrome or Chromium.
|
> Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). Puppeteer runs [headless](https://developers.google.com/web/updates/2017/04/headless-chrome) by default, but can be configured to run full (non-headless) Chrome or Chromium.
|
||||||
|
|
||||||
<!-- [START usecases] -->
|
<!-- [START usecases] -->
|
||||||
|
|
||||||
###### What can I do?
|
###### What can I do?
|
||||||
|
|
||||||
Most things that you can do manually in the browser can be done using Puppeteer! Here are a few examples to get you started:
|
Most things that you can do manually in the browser can be done using Puppeteer! Here are a few examples to get you started:
|
||||||
|
|
||||||
* Generate screenshots and PDFs of pages.
|
- Generate screenshots and PDFs of pages.
|
||||||
* Crawl a SPA (Single-Page Application) and generate pre-rendered content (i.e. "SSR" (Server-Side Rendering)).
|
- Crawl a SPA (Single-Page Application) and generate pre-rendered content (i.e. "SSR" (Server-Side Rendering)).
|
||||||
* Automate form submission, UI testing, keyboard input, etc.
|
- Automate form submission, UI testing, keyboard input, etc.
|
||||||
* Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.
|
- Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.
|
||||||
* Capture a [timeline trace](https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference) of your site to help diagnose performance issues.
|
- Capture a [timeline trace](https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference) of your site to help diagnose performance issues.
|
||||||
* Test Chrome Extensions.
|
- Test Chrome Extensions.
|
||||||
<!-- [END usecases] -->
|
<!-- [END usecases] -->
|
||||||
|
|
||||||
Give it a spin: https://try-puppeteer.appspot.com/
|
Give it a spin: https://try-puppeteer.appspot.com/
|
||||||
|
|
||||||
<!-- [START getstarted] -->
|
<!-- [START getstarted] -->
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
### Installation
|
### Installation
|
||||||
@ -39,7 +43,6 @@ npm i puppeteer
|
|||||||
|
|
||||||
Note: When you install Puppeteer, it downloads a recent version of Chromium (~170MB Mac, ~282MB Linux, ~280MB Win) that is guaranteed to work with the API. To skip the download, or to download a different browser, see [Environment variables](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#environment-variables).
|
Note: When you install Puppeteer, it downloads a recent version of Chromium (~170MB Mac, ~282MB Linux, ~280MB Win) that is guaranteed to work with the API. To skip the download, or to download a different browser, see [Environment variables](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#environment-variables).
|
||||||
|
|
||||||
|
|
||||||
### puppeteer-core
|
### puppeteer-core
|
||||||
|
|
||||||
Since version 1.7.0 we publish the [`puppeteer-core`](https://www.npmjs.com/package/puppeteer-core) package,
|
Since version 1.7.0 we publish the [`puppeteer-core`](https://www.npmjs.com/package/puppeteer-core) package,
|
||||||
@ -65,7 +68,7 @@ Node 8.9.0+. Starting from v3.0.0 Puppeteer starts to rely on Node 10.18.1+. All
|
|||||||
Puppeteer will be familiar to people using other browser testing frameworks. You create an instance
|
Puppeteer will be familiar to people using other browser testing frameworks. You create an instance
|
||||||
of `Browser`, open pages, and then manipulate them with [Puppeteer's API](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#).
|
of `Browser`, open pages, and then manipulate them with [Puppeteer's API](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#).
|
||||||
|
|
||||||
**Example** - navigating to https://example.com and saving a screenshot as *example.png*:
|
**Example** - navigating to https://example.com and saving a screenshot as _example.png_:
|
||||||
|
|
||||||
Save file as **example.js**
|
Save file as **example.js**
|
||||||
|
|
||||||
@ -76,7 +79,7 @@ const puppeteer = require('puppeteer');
|
|||||||
const browser = await puppeteer.launch();
|
const browser = await puppeteer.launch();
|
||||||
const page = await browser.newPage();
|
const page = await browser.newPage();
|
||||||
await page.goto('https://example.com');
|
await page.goto('https://example.com');
|
||||||
await page.screenshot({path: 'example.png'});
|
await page.screenshot({ path: 'example.png' });
|
||||||
|
|
||||||
await browser.close();
|
await browser.close();
|
||||||
})();
|
})();
|
||||||
@ -88,7 +91,7 @@ Execute script on the command line
|
|||||||
node example.js
|
node example.js
|
||||||
```
|
```
|
||||||
|
|
||||||
Puppeteer sets an initial page size to 800×600px, which defines the screenshot size. The page size can be customized with [`Page.setViewport()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#pagesetviewportviewport).
|
Puppeteer sets an initial page size to 800×600px, which defines the screenshot size. The page size can be customized with [`Page.setViewport()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#pagesetviewportviewport).
|
||||||
|
|
||||||
**Example** - create a PDF.
|
**Example** - create a PDF.
|
||||||
|
|
||||||
@ -100,8 +103,10 @@ const puppeteer = require('puppeteer');
|
|||||||
(async () => {
|
(async () => {
|
||||||
const browser = await puppeteer.launch();
|
const browser = await puppeteer.launch();
|
||||||
const page = await browser.newPage();
|
const page = await browser.newPage();
|
||||||
await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});
|
await page.goto('https://news.ycombinator.com', {
|
||||||
await page.pdf({path: 'hn.pdf', format: 'A4'});
|
waitUntil: 'networkidle2',
|
||||||
|
});
|
||||||
|
await page.pdf({ path: 'hn.pdf', format: 'A4' });
|
||||||
|
|
||||||
await browser.close();
|
await browser.close();
|
||||||
})();
|
})();
|
||||||
@ -132,7 +137,7 @@ const puppeteer = require('puppeteer');
|
|||||||
return {
|
return {
|
||||||
width: document.documentElement.clientWidth,
|
width: document.documentElement.clientWidth,
|
||||||
height: document.documentElement.clientHeight,
|
height: document.documentElement.clientHeight,
|
||||||
deviceScaleFactor: window.devicePixelRatio
|
deviceScaleFactor: window.devicePixelRatio,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -153,6 +158,7 @@ See [`Page.evaluate()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/
|
|||||||
<!-- [END getstarted] -->
|
<!-- [END getstarted] -->
|
||||||
|
|
||||||
<!-- [START runtimesettings] -->
|
<!-- [START runtimesettings] -->
|
||||||
|
|
||||||
## Default runtime settings
|
## Default runtime settings
|
||||||
|
|
||||||
**1. Uses Headless mode**
|
**1. Uses Headless mode**
|
||||||
@ -160,7 +166,7 @@ See [`Page.evaluate()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/
|
|||||||
Puppeteer launches Chromium in [headless mode](https://developers.google.com/web/updates/2017/04/headless-chrome). To launch a full version of Chromium, set the [`headless` option](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions) when launching a browser:
|
Puppeteer launches Chromium in [headless mode](https://developers.google.com/web/updates/2017/04/headless-chrome). To launch a full version of Chromium, set the [`headless` option](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions) when launching a browser:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const browser = await puppeteer.launch({headless: false}); // default is true
|
const browser = await puppeteer.launch({ headless: false }); // default is true
|
||||||
```
|
```
|
||||||
|
|
||||||
**2. Runs a bundled version of Chromium**
|
**2. Runs a bundled version of Chromium**
|
||||||
@ -170,7 +176,7 @@ is guaranteed to work out of the box. To use Puppeteer with a different version
|
|||||||
pass in the executable's path when creating a `Browser` instance:
|
pass in the executable's path when creating a `Browser` instance:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const browser = await puppeteer.launch({executablePath: '/path/to/Chrome'});
|
const browser = await puppeteer.launch({ executablePath: '/path/to/Chrome' });
|
||||||
```
|
```
|
||||||
|
|
||||||
You can also use Puppeteer with Firefox Nightly (experimental support). See [`Puppeteer.launch()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions) for more information.
|
You can also use Puppeteer with Firefox Nightly (experimental support). See [`Puppeteer.launch()`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions) for more information.
|
||||||
@ -189,39 +195,38 @@ Puppeteer creates its own browser user profile which it **cleans up on every run
|
|||||||
- [Examples](https://github.com/puppeteer/puppeteer/tree/main/examples/)
|
- [Examples](https://github.com/puppeteer/puppeteer/tree/main/examples/)
|
||||||
- [Community list of Puppeteer resources](https://github.com/transitive-bullshit/awesome-puppeteer)
|
- [Community list of Puppeteer resources](https://github.com/transitive-bullshit/awesome-puppeteer)
|
||||||
|
|
||||||
|
|
||||||
<!-- [START debugging] -->
|
<!-- [START debugging] -->
|
||||||
|
|
||||||
## Debugging tips
|
## Debugging tips
|
||||||
|
|
||||||
1. Turn off headless mode - sometimes it's useful to see what the browser is
|
1. Turn off headless mode - sometimes it's useful to see what the browser is
|
||||||
displaying. Instead of launching in headless mode, launch a full version of
|
displaying. Instead of launching in headless mode, launch a full version of
|
||||||
the browser using `headless: false`:
|
the browser using `headless: false`:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const browser = await puppeteer.launch({headless: false});
|
const browser = await puppeteer.launch({ headless: false });
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Slow it down - the `slowMo` option slows down Puppeteer operations by the
|
2. Slow it down - the `slowMo` option slows down Puppeteer operations by the
|
||||||
specified amount of milliseconds. It's another way to help see what's going on.
|
specified amount of milliseconds. It's another way to help see what's going on.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const browser = await puppeteer.launch({
|
const browser = await puppeteer.launch({
|
||||||
headless: false,
|
headless: false,
|
||||||
slowMo: 250 // slow down by 250ms
|
slowMo: 250, // slow down by 250ms
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Capture console output - You can listen for the `console` event.
|
3. Capture console output - You can listen for the `console` event.
|
||||||
This is also handy when debugging code in `page.evaluate()`:
|
This is also handy when debugging code in `page.evaluate()`:
|
||||||
|
|
||||||
```js
|
```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}`));
|
await page.evaluate(() => console.log(`url is ${location.href}`));
|
||||||
```
|
```
|
||||||
|
|
||||||
4. Use debugger in application code browser
|
4. Use debugger in application code browser
|
||||||
|
|
||||||
There are two execution context: node.js that is running test code, and the browser
|
There are two execution context: node.js that is running test code, and the browser
|
||||||
running application code being tested. This lets you debug code in the
|
running application code being tested. This lets you debug code in the
|
||||||
@ -230,26 +235,28 @@ Puppeteer creates its own browser user profile which it **cleans up on every run
|
|||||||
- Use `{devtools: true}` when launching Puppeteer:
|
- Use `{devtools: true}` when launching Puppeteer:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const browser = await puppeteer.launch({devtools: true});
|
const browser = await puppeteer.launch({ devtools: true });
|
||||||
```
|
```
|
||||||
|
|
||||||
- Change default test timeout:
|
- Change default test timeout:
|
||||||
|
|
||||||
jest: `jest.setTimeout(100000);`
|
jest: `jest.setTimeout(100000);`
|
||||||
|
|
||||||
jasmine: `jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;`
|
jasmine: `jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;`
|
||||||
|
|
||||||
mocha: `this.timeout(100000);` (don't forget to change test to use [function and not '=>'](https://stackoverflow.com/a/23492442))
|
mocha: `this.timeout(100000);` (don't forget to change test to use [function and not '=>'](https://stackoverflow.com/a/23492442))
|
||||||
|
|
||||||
- Add an evaluate statement with `debugger` inside / add `debugger` to an existing evaluate statement:
|
- Add an evaluate statement with `debugger` inside / add `debugger` to an existing evaluate statement:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
await page.evaluate(() => {debugger;});
|
await page.evaluate(() => {
|
||||||
|
debugger;
|
||||||
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
The test will now stop executing in the above evaluate statement, and chromium will stop in debug mode.
|
The test will now stop executing in the above evaluate statement, and chromium will stop in debug mode.
|
||||||
|
|
||||||
5. Use debugger in node.js
|
5. Use debugger in node.js
|
||||||
|
|
||||||
This will let you debug test code. For example, you can step over `await page.click()` in the node.js script and see the click happen in the application code browser.
|
This will let you debug test code. For example, you can step over `await page.click()` in the node.js script and see the click happen in the application code browser.
|
||||||
|
|
||||||
@ -270,37 +277,36 @@ Puppeteer creates its own browser user profile which it **cleans up on every run
|
|||||||
- In the newly opened test browser, type `F8` to resume test execution
|
- In the newly opened test browser, type `F8` to resume test execution
|
||||||
- Now your `debugger` will be hit and you can debug in the test browser
|
- Now your `debugger` will be hit and you can debug in the test browser
|
||||||
|
|
||||||
|
6. Enable verbose logging - internal DevTools protocol traffic
|
||||||
|
will be logged via the [`debug`](https://github.com/visionmedia/debug) module under the `puppeteer` namespace.
|
||||||
|
|
||||||
6. Enable verbose logging - internal DevTools protocol traffic
|
# Basic verbose logging
|
||||||
will be logged via the [`debug`](https://github.com/visionmedia/debug) module under the `puppeteer` namespace.
|
env DEBUG="puppeteer:*" node script.js
|
||||||
|
|
||||||
# Basic verbose logging
|
# Protocol traffic can be rather noisy. This example filters out all Network domain messages
|
||||||
env DEBUG="puppeteer:*" node script.js
|
env DEBUG="puppeteer:*" env DEBUG_COLORS=true node script.js 2>&1 | grep -v '"Network'
|
||||||
|
|
||||||
# Protocol traffic can be rather noisy. This example filters out all Network domain messages
|
7. Debug your Puppeteer (node) code easily, using [ndb](https://github.com/GoogleChromeLabs/ndb)
|
||||||
env DEBUG="puppeteer:*" env DEBUG_COLORS=true node script.js 2>&1 | grep -v '"Network'
|
|
||||||
|
|
||||||
7. Debug your Puppeteer (node) code easily, using [ndb](https://github.com/GoogleChromeLabs/ndb)
|
- `npm install -g ndb` (or even better, use [npx](https://github.com/zkat/npx)!)
|
||||||
|
|
||||||
- `npm install -g ndb` (or even better, use [npx](https://github.com/zkat/npx)!)
|
- add a `debugger` to your Puppeteer (node) code
|
||||||
|
|
||||||
- add a `debugger` to your Puppeteer (node) code
|
- add `ndb` (or `npx ndb`) before your test command. For example:
|
||||||
|
|
||||||
- add `ndb` (or `npx ndb`) before your test command. For example:
|
`ndb jest` or `ndb mocha` (or `npx ndb jest` / `npx ndb mocha`)
|
||||||
|
|
||||||
`ndb jest` or `ndb mocha` (or `npx ndb jest` / `npx ndb mocha`)
|
- debug your test inside chromium like a boss!
|
||||||
|
|
||||||
- debug your test inside chromium like a boss!
|
|
||||||
|
|
||||||
<!-- [END debugging] -->
|
<!-- [END debugging] -->
|
||||||
|
|
||||||
|
|
||||||
<!-- [START typescript] -->
|
<!-- [START typescript] -->
|
||||||
|
|
||||||
## Usage with TypeScript
|
## Usage with TypeScript
|
||||||
|
|
||||||
We have recently completed a migration to move the Puppeteer source code from JavaScript to TypeScript and we're currently working on shipping type definitions for TypeScript with Puppeteer's npm package.
|
We have recently completed a migration to move the Puppeteer source code from JavaScript to TypeScript and as of version 7.0.1 we ship our own built-in type definitions.
|
||||||
|
|
||||||
Until this work is complete we recommend installing the Puppeteer type definitions from the [DefinitelyTyped](https://definitelytyped.org/) repository:
|
If you are on a version older than 7, we recommend installing the Puppeteer type definitions from the [DefinitelyTyped](https://definitelytyped.org/) repository:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install --save-dev @types/puppeteer
|
npm install --save-dev @types/puppeteer
|
||||||
@ -310,7 +316,6 @@ The types that you'll see appearing in the Puppeteer source code are based off t
|
|||||||
|
|
||||||
<!-- [END typescript] -->
|
<!-- [END typescript] -->
|
||||||
|
|
||||||
|
|
||||||
## Contributing to Puppeteer
|
## Contributing to Puppeteer
|
||||||
|
|
||||||
Check out [contributing guide](https://github.com/puppeteer/puppeteer/blob/main/CONTRIBUTING.md) to get an overview of Puppeteer development.
|
Check out [contributing guide](https://github.com/puppeteer/puppeteer/blob/main/CONTRIBUTING.md) to get an overview of Puppeteer development.
|
||||||
@ -344,6 +349,7 @@ The goals of the project are:
|
|||||||
- Learn more about the pain points of automated browser testing and help fill those gaps.
|
- Learn more about the pain points of automated browser testing and help fill those gaps.
|
||||||
|
|
||||||
We adapt [Chromium principles](https://www.chromium.org/developers/core-principles) to help us drive product decisions:
|
We adapt [Chromium principles](https://www.chromium.org/developers/core-principles) to help us drive product decisions:
|
||||||
|
|
||||||
- **Speed**: Puppeteer has almost zero performance overhead over an automated page.
|
- **Speed**: Puppeteer has almost zero performance overhead over an automated page.
|
||||||
- **Security**: Puppeteer operates off-process with respect to Chromium, making it safe to automate potentially malicious pages.
|
- **Security**: Puppeteer operates off-process with respect to Chromium, making it safe to automate potentially malicious pages.
|
||||||
- **Stability**: Puppeteer should not be flaky and should not leak memory.
|
- **Stability**: Puppeteer should not be flaky and should not leak memory.
|
||||||
@ -352,6 +358,7 @@ We adapt [Chromium principles](https://www.chromium.org/developers/core-principl
|
|||||||
#### Q: Is Puppeteer replacing Selenium/WebDriver?
|
#### Q: Is Puppeteer replacing Selenium/WebDriver?
|
||||||
|
|
||||||
**No**. Both projects are valuable for very different reasons:
|
**No**. Both projects are valuable for very different reasons:
|
||||||
|
|
||||||
- Selenium/WebDriver focuses on cross-browser automation; its value proposition is a single standard API that works across all major browsers.
|
- Selenium/WebDriver focuses on cross-browser automation; its value proposition is a single standard API that works across all major browsers.
|
||||||
- Puppeteer focuses on Chromium; its value proposition is richer functionality and higher reliability.
|
- Puppeteer focuses on Chromium; its value proposition is richer functionality and higher reliability.
|
||||||
|
|
||||||
@ -367,6 +374,7 @@ That said, you **can** use Puppeteer to run tests against Chromium, e.g. using t
|
|||||||
We see Puppeteer as an **indivisible entity** with Chromium. Each version of Puppeteer bundles a specific version of Chromium – **the only** version it is guaranteed to work with.
|
We see Puppeteer as an **indivisible entity** with Chromium. Each version of Puppeteer bundles a specific version of Chromium – **the only** version it is guaranteed to work with.
|
||||||
|
|
||||||
This is not an artificial constraint: A lot of work on Puppeteer is actually taking place in the Chromium repository. Here’s a typical story:
|
This is not an artificial constraint: A lot of work on Puppeteer is actually taking place in the Chromium repository. Here’s a typical story:
|
||||||
|
|
||||||
- A Puppeteer bug is reported: https://github.com/puppeteer/puppeteer/issues/2709
|
- A Puppeteer bug is reported: https://github.com/puppeteer/puppeteer/issues/2709
|
||||||
- It turned out this is an issue with the DevTools protocol, so we’re fixing it in Chromium: https://chromium-review.googlesource.com/c/chromium/src/+/1102154
|
- It turned out this is an issue with the DevTools protocol, so we’re fixing it in Chromium: https://chromium-review.googlesource.com/c/chromium/src/+/1102154
|
||||||
- Once the upstream fix is landed, we roll updated Chromium into Puppeteer: https://github.com/puppeteer/puppeteer/pull/2769
|
- Once the upstream fix is landed, we roll updated Chromium into Puppeteer: https://github.com/puppeteer/puppeteer/pull/2769
|
||||||
@ -374,6 +382,7 @@ This is not an artificial constraint: A lot of work on Puppeteer is actually tak
|
|||||||
However, oftentimes it is desirable to use Puppeteer with the official Google Chrome rather than Chromium. For this to work, you should install a `puppeteer-core` version that corresponds to the Chrome version.
|
However, oftentimes it is desirable to use Puppeteer with the official Google Chrome rather than Chromium. For this to work, you should install a `puppeteer-core` version that corresponds to the Chrome version.
|
||||||
|
|
||||||
For example, in order to drive Chrome 71 with puppeteer-core, use `chrome-71` npm tag:
|
For example, in order to drive Chrome 71 with puppeteer-core, use `chrome-71` npm tag:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install puppeteer-core@chrome-71
|
npm install puppeteer-core@chrome-71
|
||||||
```
|
```
|
||||||
@ -382,7 +391,6 @@ npm install puppeteer-core@chrome-71
|
|||||||
|
|
||||||
Look for the `chromium` entry in [revisions.ts](https://github.com/puppeteer/puppeteer/blob/main/src/revisions.ts). To find the corresponding Chromium commit and version number, search for the revision prefixed by an `r` in [OmahaProxy](https://omahaproxy.appspot.com/)'s "Find Releases" section.
|
Look for the `chromium` entry in [revisions.ts](https://github.com/puppeteer/puppeteer/blob/main/src/revisions.ts). To find the corresponding Chromium commit and version number, search for the revision prefixed by an `r` in [OmahaProxy](https://omahaproxy.appspot.com/)'s "Find Releases" section.
|
||||||
|
|
||||||
|
|
||||||
#### Q: Which Firefox version does Puppeteer use?
|
#### Q: Which Firefox version does Puppeteer use?
|
||||||
|
|
||||||
Since Firefox support is experimental, Puppeteer downloads the latest [Firefox Nightly](https://wiki.mozilla.org/Nightly) when the `PUPPETEER_PRODUCT` environment variable is set to `firefox`. That's also why the value of `firefox` in [revisions.ts](https://github.com/puppeteer/puppeteer/blob/main/src/revisions.ts) is `latest` -- Puppeteer isn't tied to a particular Firefox version.
|
Since Firefox support is experimental, Puppeteer downloads the latest [Firefox Nightly](https://wiki.mozilla.org/Nightly) when the `PUPPETEER_PRODUCT` environment variable is set to `firefox`. That's also why the value of `firefox` in [revisions.ts](https://github.com/puppeteer/puppeteer/blob/main/src/revisions.ts) is `latest` -- Puppeteer isn't tied to a particular Firefox version.
|
||||||
@ -409,6 +417,7 @@ In browsers, input events could be divided into two big groups: trusted vs. untr
|
|||||||
- **Untrusted event**: events generated by Web APIs, e.g. `document.createEvent` or `element.click()` methods.
|
- **Untrusted event**: events generated by Web APIs, e.g. `document.createEvent` or `element.click()` methods.
|
||||||
|
|
||||||
Websites can distinguish between these two groups:
|
Websites can distinguish between these two groups:
|
||||||
|
|
||||||
- using an [`Event.isTrusted`](https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted) event flag
|
- using an [`Event.isTrusted`](https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted) event flag
|
||||||
- sniffing for accompanying events. For example, every trusted `'click'` event is preceded by `'mousedown'` and `'mouseup'` events.
|
- sniffing for accompanying events. For example, every trusted `'click'` event is preceded by `'mousedown'` and `'mouseup'` events.
|
||||||
|
|
||||||
@ -424,10 +433,11 @@ await page.evaluate(() => {
|
|||||||
|
|
||||||
You may find that Puppeteer does not behave as expected when controlling pages that incorporate audio and video. (For example, [video playback/screenshots is likely to fail](https://github.com/puppeteer/puppeteer/issues/291).) There are two reasons for this:
|
You may find that Puppeteer does not behave as expected when controlling pages that incorporate audio and video. (For example, [video playback/screenshots is likely to fail](https://github.com/puppeteer/puppeteer/issues/291).) There are two reasons for this:
|
||||||
|
|
||||||
* Puppeteer is bundled with Chromium — not Chrome — and so by default, it inherits all of [Chromium's media-related limitations](https://www.chromium.org/audio-video). This means that Puppeteer does not support licensed formats such as AAC or H.264. (However, it is possible to force Puppeteer to use a separately-installed version Chrome instead of Chromium via the [`executablePath` option to `puppeteer.launch`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions). You should only use this configuration if you need an official release of Chrome that supports these media formats.)
|
- Puppeteer is bundled with Chromium — not Chrome — and so by default, it inherits all of [Chromium's media-related limitations](https://www.chromium.org/audio-video). This means that Puppeteer does not support licensed formats such as AAC or H.264. (However, it is possible to force Puppeteer to use a separately-installed version Chrome instead of Chromium via the [`executablePath` option to `puppeteer.launch`](https://github.com/puppeteer/puppeteer/blob/v7.0.1/docs/api.md#puppeteerlaunchoptions). You should only use this configuration if you need an official release of Chrome that supports these media formats.)
|
||||||
* Since Puppeteer (in all configurations) controls a desktop version of Chromium/Chrome, features that are only supported by the mobile version of Chrome are not supported. This means that Puppeteer [does not support HTTP Live Streaming (HLS)](https://caniuse.com/#feat=http-live-streaming).
|
- Since Puppeteer (in all configurations) controls a desktop version of Chromium/Chrome, features that are only supported by the mobile version of Chrome are not supported. This means that Puppeteer [does not support HTTP Live Streaming (HLS)](https://caniuse.com/#feat=http-live-streaming).
|
||||||
|
|
||||||
#### Q: I am having trouble installing / running Puppeteer in my test environment. Where should I look for help?
|
#### Q: I am having trouble installing / running Puppeteer in my test environment. Where should I look for help?
|
||||||
|
|
||||||
We have a [troubleshooting](https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md) guide for various operating systems that lists the required dependencies.
|
We have a [troubleshooting](https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md) guide for various operating systems that lists the required dependencies.
|
||||||
|
|
||||||
#### Q: How do I try/test a prerelease version of Puppeteer?
|
#### Q: How do I try/test a prerelease version of Puppeteer?
|
||||||
@ -443,11 +453,11 @@ Please note that prerelease may be unstable and contain bugs.
|
|||||||
#### Q: I have more questions! Where do I ask?
|
#### Q: I have more questions! Where do I ask?
|
||||||
|
|
||||||
There are many ways to get help on Puppeteer:
|
There are many ways to get help on Puppeteer:
|
||||||
|
|
||||||
- [bugtracker](https://github.com/puppeteer/puppeteer/issues)
|
- [bugtracker](https://github.com/puppeteer/puppeteer/issues)
|
||||||
- [Stack Overflow](https://stackoverflow.com/questions/tagged/puppeteer)
|
- [Stack Overflow](https://stackoverflow.com/questions/tagged/puppeteer)
|
||||||
- [slack channel](https://join.slack.com/t/puppeteer/shared_invite/enQtMzU4MjIyMDA5NTM4LWI0YTE0MjM0NWQzYmE2MTRmNjM1ZTBkN2MxNmJmNTIwNTJjMmFhOWFjMGExMDViYjk2YjU2ZmYzMmE1NmExYzc)
|
- [slack channel](https://join.slack.com/t/puppeteer/shared_invite/enQtMzU4MjIyMDA5NTM4LWI0YTE0MjM0NWQzYmE2MTRmNjM1ZTBkN2MxNmJmNTIwNTJjMmFhOWFjMGExMDViYjk2YjU2ZmYzMmE1NmExYzc)
|
||||||
|
|
||||||
Make sure to search these channels before posting your question.
|
Make sure to search these channels before posting your question.
|
||||||
|
|
||||||
|
|
||||||
<!-- [END faq] -->
|
<!-- [END faq] -->
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
|
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
|
||||||
"mainEntryPointFilePath": "<projectFolder>/lib/cjs/puppeteer/api-docs-entry.d.ts",
|
"mainEntryPointFilePath": "<projectFolder>/lib/cjs/puppeteer/api-docs-entry.d.ts",
|
||||||
"bundledPackages": [ "devtools-protocol" ],
|
"bundledPackages": ["devtools-protocol"],
|
||||||
|
|
||||||
"apiReport": {
|
"apiReport": {
|
||||||
"enabled": false
|
"enabled": false
|
||||||
@ -12,7 +12,8 @@
|
|||||||
},
|
},
|
||||||
|
|
||||||
"dtsRollup": {
|
"dtsRollup": {
|
||||||
"enabled": false
|
"enabled": true,
|
||||||
|
"untrimmedFilePath": "lib/types.d.ts"
|
||||||
},
|
},
|
||||||
|
|
||||||
"tsdocMetadata": {
|
"tsdocMetadata": {
|
||||||
@ -41,5 +42,4 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
3
cjs-entry.d.ts
vendored
3
cjs-entry.d.ts
vendored
@ -1,3 +0,0 @@
|
|||||||
declare const _default: typeof import('./lib/cjs/puppeteer/node').default;
|
|
||||||
|
|
||||||
export default _default;
|
|
@ -3,6 +3,7 @@
|
|||||||
"version": "7.0.1-post",
|
"version": "7.0.1-post",
|
||||||
"description": "A high-level API to control headless Chrome over the DevTools Protocol",
|
"description": "A high-level API to control headless Chrome over the DevTools Protocol",
|
||||||
"main": "./cjs-entry.js",
|
"main": "./cjs-entry.js",
|
||||||
|
"types": "lib/types.d.ts",
|
||||||
"repository": "github:puppeteer/puppeteer",
|
"repository": "github:puppeteer/puppeteer",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.18.1"
|
"node": ">=10.18.1"
|
||||||
@ -26,13 +27,14 @@
|
|||||||
"lint": "npm run eslint && npm run tsc && npm run doc && npm run commitlint",
|
"lint": "npm run eslint && npm run tsc && npm run doc && npm run commitlint",
|
||||||
"doc": "node utils/doclint/cli.js",
|
"doc": "node utils/doclint/cli.js",
|
||||||
"clean-lib": "rm -rf lib",
|
"clean-lib": "rm -rf lib",
|
||||||
"build": "npm run tsc",
|
"build": "npm run tsc && npm run generate-d-ts",
|
||||||
"tsc": "npm run clean-lib && tsc --version && npm run tsc-cjs && npm run tsc-esm",
|
"tsc": "npm run clean-lib && tsc --version && npm run tsc-cjs && npm run tsc-esm",
|
||||||
"tsc-cjs": "tsc -b src/tsconfig.cjs.json",
|
"tsc-cjs": "tsc -b src/tsconfig.cjs.json",
|
||||||
"tsc-esm": "tsc -b src/tsconfig.esm.json",
|
"tsc-esm": "tsc -b src/tsconfig.esm.json",
|
||||||
"apply-next-version": "node utils/apply_next_version.js",
|
"apply-next-version": "node utils/apply_next_version.js",
|
||||||
"test-install": "scripts/test-install.sh",
|
"test-install": "scripts/test-install.sh",
|
||||||
"generate-docs": "npm run tsc && api-extractor run --local --verbose && api-documenter markdown -i temp -o new-docs",
|
"generate-d-ts": "npm run tsc && api-extractor run --local --verbose && ts-node -s scripts/add-default-export-to-types.ts",
|
||||||
|
"generate-docs": "npm run generate-d-ts && api-documenter markdown -i temp -o new-docs",
|
||||||
"ensure-correct-devtools-protocol-revision": "ts-node -s scripts/ensure-correct-devtools-protocol-package",
|
"ensure-correct-devtools-protocol-revision": "ts-node -s scripts/ensure-correct-devtools-protocol-package",
|
||||||
"release": "node utils/remove_version_suffix.js && standard-version --commit-all"
|
"release": "node utils/remove_version_suffix.js && standard-version --commit-all"
|
||||||
},
|
},
|
||||||
@ -44,8 +46,7 @@
|
|||||||
"install.js",
|
"install.js",
|
||||||
"typescript-if-required.js",
|
"typescript-if-required.js",
|
||||||
"cjs-entry.js",
|
"cjs-entry.js",
|
||||||
"cjs-entry-core.js",
|
"cjs-entry-core.js"
|
||||||
"cjs-entry.d.ts"
|
|
||||||
],
|
],
|
||||||
"author": "The Chromium Authors",
|
"author": "The Chromium Authors",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
|
33
scripts/add-default-export-to-types.ts
Normal file
33
scripts/add-default-export-to-types.ts
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* Copyright 2021 Google Inc. All rights reserved.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import packageJson from '../package.json';
|
||||||
|
|
||||||
|
const typingsLocation = path.resolve(process.cwd(), packageJson.types);
|
||||||
|
|
||||||
|
const fileContents = fs.readFileSync(typingsLocation, { encoding: 'utf-8' });
|
||||||
|
|
||||||
|
// Default to exposing the Node package as this is the majority of our use case.
|
||||||
|
// May need reworking in the future when we ship an officially supported browser
|
||||||
|
// bundle also.
|
||||||
|
const defaultExportCode = `declare const puppeteer: PuppeteerNode;
|
||||||
|
export = puppeteer;`;
|
||||||
|
|
||||||
|
const newFileContents = fileContents + `\n${defaultExportCode}`;
|
||||||
|
|
||||||
|
fs.writeFileSync(typingsLocation, newFileContents);
|
@ -19,9 +19,7 @@ import { JSHandle, ElementHandle } from './JSHandle.js';
|
|||||||
/**
|
/**
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
export type EvaluateFn<T = unknown> =
|
export type EvaluateFn<T = any> = string | ((arg1: T, ...args: any[]) => any);
|
||||||
| string
|
|
||||||
| ((arg1: T, ...args: unknown[]) => unknown);
|
|
||||||
|
|
||||||
export type UnwrapPromiseLike<T> = T extends PromiseLike<infer U> ? U : T;
|
export type UnwrapPromiseLike<T> = T extends PromiseLike<infer U> ? U : T;
|
||||||
|
|
||||||
@ -29,15 +27,15 @@ export type UnwrapPromiseLike<T> = T extends PromiseLike<infer U> ? U : T;
|
|||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
export type EvaluateFnReturnType<T extends EvaluateFn> = T extends (
|
export type EvaluateFnReturnType<T extends EvaluateFn> = T extends (
|
||||||
...args: unknown[]
|
...args: any[]
|
||||||
) => infer R
|
) => infer R
|
||||||
? R
|
? R
|
||||||
: unknown;
|
: any;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
export type EvaluateHandleFn = string | ((...args: unknown[]) => unknown);
|
export type EvaluateHandleFn = string | ((...args: any[]) => any);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @public
|
* @public
|
||||||
|
Loading…
Reference in New Issue
Block a user