playwright-browser-handler 0.0.0-stage → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +205 -2
- package/package.json +60 -4
- package/src/browser-handler.js +299 -0
- package/src/index.d.ts +114 -0
- package/src/index.js +6 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Niv Kaufman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,206 @@
|
|
|
1
|
-
#
|
|
1
|
+
# playwright-browser-handler 🎭
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/playwright-browser-handler)
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/playwright-browser-handler)
|
|
6
|
+
[](https://www.npmjs.com/package/playwright-browser-handler)
|
|
7
|
+
[](https://github.com/nivkman/playwright-browser-handler/actions/workflows/test.yml)
|
|
8
|
+
[](./LICENSE)
|
|
9
|
+
|
|
10
|
+
A convenient wrapper around [Playwright](https://playwright.dev) for browser automation. One line to open a browser, then navigate, click, fill forms, scrape links, take screenshots and collect downloads — while keeping full access to the Playwright `page` whenever you need it.
|
|
11
|
+
|
|
12
|
+
Same API as [`puppet-browser-handler`](https://github.com/nivkman/puppet-browser-handler), now running on Playwright: Chromium, Firefox **and** WebKit, with browsers managed by Playwright instead of a hard-coded Chrome path.
|
|
13
|
+
|
|
14
|
+
## 🚀 Installation
|
|
15
|
+
|
|
16
|
+
Requires Node.js 20 or newer.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install playwright-browser-handler
|
|
20
|
+
npx playwright install chromium # once — downloads the browser (add firefox / webkit if you want them)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## ⚡ Quick Start
|
|
24
|
+
|
|
25
|
+
```javascript
|
|
26
|
+
import BrowserHandler from 'playwright-browser-handler';
|
|
27
|
+
|
|
28
|
+
const browser = new BrowserHandler('./downloads');
|
|
29
|
+
|
|
30
|
+
await browser.openBrowser();
|
|
31
|
+
await browser.goToPage('https://example.com');
|
|
32
|
+
|
|
33
|
+
const title = await browser.getText('h1');
|
|
34
|
+
const links = await browser.getElementsHrefLink('a');
|
|
35
|
+
await browser.screenshot('example', 'png'); // ./downloads/example.png
|
|
36
|
+
|
|
37
|
+
await browser.closeBrowser();
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Logging in and downloading a report:
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
await browser.openBrowser({ headless: false, slowMo: 50 });
|
|
44
|
+
await browser.goToPage('https://app.example.com/login');
|
|
45
|
+
await browser.fill('#email', process.env.EMAIL);
|
|
46
|
+
await browser.fill('#password', process.env.PASSWORD);
|
|
47
|
+
await browser.click('button[type=submit]');
|
|
48
|
+
|
|
49
|
+
if (await browser.elementExists('#dashboard')) {
|
|
50
|
+
await browser.click('#export-csv'); // lands in ./downloads automatically
|
|
51
|
+
await browser.sleep(3, 1); // human-like pause: 1–3 seconds
|
|
52
|
+
}
|
|
53
|
+
await browser.closeBrowser();
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Need something the wrapper doesn't cover? Use Playwright directly:
|
|
57
|
+
|
|
58
|
+
```javascript
|
|
59
|
+
await browser.page.getByRole('button', { name: 'Accept' }).click();
|
|
60
|
+
await browser.context.storageState({ path: 'auth.json' });
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## ✨ Features
|
|
64
|
+
|
|
65
|
+
### 🌐 Browser Management
|
|
66
|
+
- One-line launch of **Chromium, Firefox or WebKit** (or your installed Chrome/Edge via `channel`)
|
|
67
|
+
- Open and close browser sessions and tabs
|
|
68
|
+
- Set cookies before the first navigation — Chrome cookie exports work as-is
|
|
69
|
+
- Resume a saved login with `storageState` (save it with `browser.context.storageState({ path })`), with your own `userAgent`, `locale` and `timezoneId`
|
|
70
|
+
- Sensible defaults: 1920×1080 viewport, 60 s navigation timeout, headless
|
|
71
|
+
|
|
72
|
+
### 🔍 Page Navigation and Interaction
|
|
73
|
+
- Navigate to URLs, click elements, fill inputs
|
|
74
|
+
- Check element existence with a timeout
|
|
75
|
+
- Read text and absolute `href` links from one or many elements
|
|
76
|
+
- Scroll to the bottom of infinite pages
|
|
77
|
+
- Get Playwright `Locator`s for anything else
|
|
78
|
+
|
|
79
|
+
### 📥 Downloads & Screenshots
|
|
80
|
+
- Every download, on every tab, is saved into your downloads folder
|
|
81
|
+
- Full-page screenshots as PNG or JPEG, path returned
|
|
82
|
+
|
|
83
|
+
### 🛠️ Utilities
|
|
84
|
+
- Random human-like `sleep(limit, start)` delays
|
|
85
|
+
- Timestamped logging via [`logger-standard`](https://www.npmjs.com/package/logger-standard)
|
|
86
|
+
- `.d.ts` types included — great IDE support in plain JavaScript too
|
|
87
|
+
- `handler.page`, `handler.context`, `handler.browser` escape hatches, plus `chromium` / `firefox` / `webkit` / `devices` re-exported
|
|
88
|
+
|
|
89
|
+
## 📖 API Reference
|
|
90
|
+
|
|
91
|
+
### Constructor
|
|
92
|
+
|
|
93
|
+
```javascript
|
|
94
|
+
const browser = new BrowserHandler(downloadPath = './downloads', { logLevel = 'info' } = {});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Browser control
|
|
98
|
+
|
|
99
|
+
| Method | Description |
|
|
100
|
+
|--------|-------------|
|
|
101
|
+
| `openBrowser(options?)` | Launches a browser and opens the first page. See options below. |
|
|
102
|
+
| `openBrowser(cookies, headless?, slowMo?)` | Legacy `puppet-browser-handler` signature — still works. |
|
|
103
|
+
| `closeBrowser()` | Closes the browser and all its pages. |
|
|
104
|
+
| `openNewPage()` | Opens a new tab and makes it the current page. Returns the Playwright `Page`. |
|
|
105
|
+
| `closeCurrentPage()` | Closes the current tab; the last remaining tab becomes current. |
|
|
106
|
+
| `configureDownloadsFolder()` | Creates the downloads folder and routes all downloads into it (called by `openBrowser`). |
|
|
107
|
+
|
|
108
|
+
#### `openBrowser` options
|
|
109
|
+
|
|
110
|
+
| Option | Type | Default | Description |
|
|
111
|
+
|--------|------|---------|-------------|
|
|
112
|
+
| `browser` | `'chromium' \| 'firefox' \| 'webkit'` | `'chromium'` | Engine to launch |
|
|
113
|
+
| `headless` | `boolean` | `true` | Run without a visible window (`'new'` is accepted for compatibility) |
|
|
114
|
+
| `slowMo` | `number` | `30` | Milliseconds to slow each action by |
|
|
115
|
+
| `cookies` | `Cookie[]` | `null` | Cookies to set before navigating (`name`, `value` + `url` or `domain`) |
|
|
116
|
+
| `viewport` | `{ width, height } \| null` | `1920×1080` | Page size; `null` disables the fixed viewport |
|
|
117
|
+
| `navigationTimeout` | `number` | `60000` | Default navigation timeout in ms; `0` disables it |
|
|
118
|
+
| `args` | `string[]` | — | Extra command-line flags for the browser |
|
|
119
|
+
| `channel` | `string` | — | `'chrome'`, `'msedge'`… to use an installed browser |
|
|
120
|
+
| `executablePath` | `string` | — | Use a specific browser binary |
|
|
121
|
+
| `timeout` | `number` | — | Launch timeout in ms |
|
|
122
|
+
| `storageState` | `string \| StorageState` | — | Saved session to resume: a JSON file path or the object from `context.storageState()` |
|
|
123
|
+
| `userAgent` | `string` | — | User agent for the context |
|
|
124
|
+
| `locale` | `string` | — | Locale, e.g. `'en-US'` (`navigator.language`, `Accept-Language`, formatting) |
|
|
125
|
+
| `timezoneId` | `string` | — | Time zone, e.g. `'Asia/Jerusalem'` |
|
|
126
|
+
|
|
127
|
+
### Navigation & interaction
|
|
128
|
+
|
|
129
|
+
| Method | Description |
|
|
130
|
+
|--------|-------------|
|
|
131
|
+
| `goToPage(url, options?)` | Navigates to the URL. Returns the Playwright `Response`. |
|
|
132
|
+
| `click(selector, options?)` | Waits for a visible match (`options.timeout` ms, default 5000), then clicks it. Throws if none appears. |
|
|
133
|
+
| `fill(selector, text, options?)` | Fills an input, textarea or contenteditable. |
|
|
134
|
+
| `getText(selector)` | Trimmed visible text of the first match. |
|
|
135
|
+
| `elementExists(selector, timeout = 5000)` | `true` if a visible match appears within the timeout, else `false`. |
|
|
136
|
+
| `getElementHrefLink(selector)` | Absolute `href` of the first match. |
|
|
137
|
+
| `getElementsHrefLink(selector)` | Absolute `href` of every match (elements without one are skipped). |
|
|
138
|
+
| `getElementBySelector(selector)` | Playwright `Locator` for the first match. |
|
|
139
|
+
| `getElementsBySelector(selector)` | Array of `Locator`s, one per match. |
|
|
140
|
+
| `isElementDisabled(locator)` | `true` if the element is disabled. |
|
|
141
|
+
| `scrollDown(distance = 1000, delay = 1000)` | Scrolls `distance` px every `delay` ms until the bottom. |
|
|
142
|
+
|
|
143
|
+
### Utilities
|
|
144
|
+
|
|
145
|
+
| Method | Description |
|
|
146
|
+
|--------|-------------|
|
|
147
|
+
| `screenshot(fileName, fileExt = 'png', options?)` | Full-page screenshot saved as `<downloadPath>/<fileName>.<fileExt>` (`png`, `jpg`, `jpeg`). Returns the path. |
|
|
148
|
+
| `sleep(limit, start = 0)` | Waits a random number of **seconds** between `start` and `limit`. |
|
|
149
|
+
|
|
150
|
+
### Properties
|
|
151
|
+
|
|
152
|
+
| Property | Description |
|
|
153
|
+
|----------|-------------|
|
|
154
|
+
| `page` | Current Playwright [`Page`](https://playwright.dev/docs/api/class-page) (`null` until `openBrowser`) |
|
|
155
|
+
| `context` | Playwright [`BrowserContext`](https://playwright.dev/docs/api/class-browsercontext) |
|
|
156
|
+
| `browser` | Playwright [`Browser`](https://playwright.dev/docs/api/class-browser) |
|
|
157
|
+
| `downloadPath` | Folder for screenshots and downloads |
|
|
158
|
+
|
|
159
|
+
## 🔁 Migrating from puppet-browser-handler
|
|
160
|
+
|
|
161
|
+
Swap the import — the method names and signatures are the same. What changed:
|
|
162
|
+
|
|
163
|
+
| | `puppet-browser-handler` | `playwright-browser-handler` |
|
|
164
|
+
|---|---|---|
|
|
165
|
+
| Engine | Puppeteer + Chrome at `/usr/bin/google-chrome` | Playwright-managed Chromium, Firefox or WebKit |
|
|
166
|
+
| Browser install | Install Chrome yourself | `npx playwright install chromium` |
|
|
167
|
+
| `openBrowser()` | `(cookies, headless = 'new', slowMo)` | Same, **or** an options object |
|
|
168
|
+
| Failures | Many methods logged the error and continued | Methods log **and throw**, so you can `try/catch` |
|
|
169
|
+
| `click()` / `getElementHrefLink()` | Existence check didn't actually wait | Waits up to 5 s, then throws a clear error |
|
|
170
|
+
| `screenshot(name, 'jpg')` | Always wrote PNG data | Writes real JPEG |
|
|
171
|
+
| `getElementsHrefLink()` etc. | Needed `cheerio` (which wasn't imported) | Pure Playwright — no extra dependency |
|
|
172
|
+
| Downloads | Current tab only, via CDP | Every tab, including popups |
|
|
173
|
+
| Element results | cheerio objects | Playwright `Locator`s |
|
|
174
|
+
| Types | — | `.d.ts` included |
|
|
175
|
+
|
|
176
|
+
New: `fill(selector, text)`, `getText(selector)`, and the `page` / `context` / `browser` properties.
|
|
177
|
+
|
|
178
|
+
## 🤔 Why playwright-browser-handler?
|
|
179
|
+
|
|
180
|
+
Playwright gives you three engines, auto-waiting, managed browser binaries and first-class downloads. This package keeps the small, readable API you already know from `puppet-browser-handler` on top of it, so a scraping or automation script is a handful of lines — and when you outgrow the wrapper, `browser.page` is the real Playwright page. Nothing to unlearn.
|
|
181
|
+
|
|
182
|
+
## 🔒 Error Handling & Logging
|
|
183
|
+
|
|
184
|
+
Every operation is logged with a timestamp and the `BrowserHandler` service prefix via `logger-standard`. Errors are logged and then thrown, so wrap your flow in `try/catch` and always `closeBrowser()` in a `finally`. Set `{ logLevel: 'error' }` in the constructor to quiet things down.
|
|
185
|
+
|
|
186
|
+
## 🧪 Tests
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
npm install
|
|
190
|
+
npx playwright install chromium
|
|
191
|
+
npm test
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
The suite runs a real headless Chromium against a local fixture server — no network needed.
|
|
195
|
+
|
|
196
|
+
## 📄 License
|
|
197
|
+
|
|
198
|
+
MIT
|
|
199
|
+
|
|
200
|
+
## 👥 Contributing
|
|
201
|
+
|
|
202
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
203
|
+
|
|
204
|
+
## 🐛 Issues
|
|
205
|
+
|
|
206
|
+
If you find a bug or want to request a new feature, please [open an issue](https://github.com/nivkman/playwright-browser-handler/issues).
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "playwright-browser-handler",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"description": "A convenient Playwright wrapper for browser automation. One line to open a browser, then navigate, click, fill forms, scrape links, take screenshots and collect downloads — with full access to Playwright underneath. Same API as puppet-browser-handler.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"types": "src/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.d.ts",
|
|
11
|
+
"import": "./src/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20.0.0"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node --test test/*.test.js"
|
|
19
|
+
},
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/nivkman/playwright-browser-handler.git"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"playwright",
|
|
26
|
+
"browser",
|
|
27
|
+
"automation",
|
|
28
|
+
"headless",
|
|
29
|
+
"chromium",
|
|
30
|
+
"firefox",
|
|
31
|
+
"webkit",
|
|
32
|
+
"scraping",
|
|
33
|
+
"screenshots",
|
|
34
|
+
"downloads",
|
|
35
|
+
"web-automation",
|
|
36
|
+
"browser-automation",
|
|
37
|
+
"crawler",
|
|
38
|
+
"page-automation",
|
|
39
|
+
"web-testing",
|
|
40
|
+
"e2e",
|
|
41
|
+
"nodejs",
|
|
42
|
+
"wrapper",
|
|
43
|
+
"browser-handler",
|
|
44
|
+
"puppeteer-alternative"
|
|
45
|
+
],
|
|
46
|
+
"author": "Niv Kaufman",
|
|
47
|
+
"license": "MIT",
|
|
48
|
+
"bugs": {
|
|
49
|
+
"url": "https://github.com/nivkman/playwright-browser-handler/issues"
|
|
50
|
+
},
|
|
51
|
+
"homepage": "https://github.com/nivkman/playwright-browser-handler#readme",
|
|
52
|
+
"files": [
|
|
53
|
+
"src/"
|
|
54
|
+
],
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"logger-standard": "^2.0.0",
|
|
57
|
+
"playwright": "^1.64.1"
|
|
58
|
+
},
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"access": "public"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { chromium, firefox, webkit } from "playwright";
|
|
2
|
+
import { Logger } from "logger-standard";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
const SERVICE_NAME = "BrowserHandler";
|
|
7
|
+
const ENGINES = { chromium, firefox, webkit };
|
|
8
|
+
const DEFAULT_VIEWPORT = { width: 1920, height: 1080 };
|
|
9
|
+
const DEFAULT_NAVIGATION_TIMEOUT = 60_000;
|
|
10
|
+
const COOKIE_FIELDS = ["name", "value", "url", "domain", "path", "expires", "httpOnly", "secure", "sameSite"];
|
|
11
|
+
const SAME_SITE = { strict: "Strict", lax: "Lax", none: "None", no_restriction: "None" };
|
|
12
|
+
const CONTEXT_FIELDS = ["storageState", "userAgent", "locale", "timezoneId"];
|
|
13
|
+
|
|
14
|
+
export default class BrowserHandler {
|
|
15
|
+
/**
|
|
16
|
+
* @param {string} [downloadPath="./downloads"] Where screenshots and downloads are saved.
|
|
17
|
+
* @param {{ logLevel?: "debug"|"info"|"warn"|"error" }} [options]
|
|
18
|
+
*/
|
|
19
|
+
constructor(downloadPath = "./downloads", { logLevel = "info" } = {}) {
|
|
20
|
+
this._logger = new Logger({ service: SERVICE_NAME, showDate: true, logLevel });
|
|
21
|
+
this._browser = null;
|
|
22
|
+
this._context = null;
|
|
23
|
+
this._page = null;
|
|
24
|
+
this._watched = new WeakSet();
|
|
25
|
+
this._navigationTimeout = DEFAULT_NAVIGATION_TIMEOUT;
|
|
26
|
+
this.downloadPath = downloadPath;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The underlying Playwright Browser (null until openBrowser). */
|
|
30
|
+
get browser() {
|
|
31
|
+
return this._browser;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The underlying Playwright BrowserContext (null until openBrowser). */
|
|
35
|
+
get context() {
|
|
36
|
+
return this._context;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The current Playwright Page — your escape hatch to the full Playwright API. */
|
|
40
|
+
get page() {
|
|
41
|
+
return this._page;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ─── Browser lifecycle ────────────────────────────────────────────────────
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Launches a browser and opens the first page.
|
|
48
|
+
* Accepts an options object, or the legacy `(cookies, headless, slowMo)` arguments.
|
|
49
|
+
*/
|
|
50
|
+
async openBrowser(cookiesOrOptions = null, headless = true, slowMo = 30) {
|
|
51
|
+
const options = normalizeOpenOptions(cookiesOrOptions, headless, slowMo);
|
|
52
|
+
try {
|
|
53
|
+
await this._launch(options);
|
|
54
|
+
await this.configureDownloadsFolder();
|
|
55
|
+
await this._setCookies(options.cookies);
|
|
56
|
+
this._logger.info(`${options.browser} browser initialized successfully`);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
await this._browser?.close().catch(() => {});
|
|
59
|
+
this._browser = this._context = this._page = null;
|
|
60
|
+
this._fail(error);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async _launch(options) {
|
|
65
|
+
const engine = ENGINES[options.browser];
|
|
66
|
+
if (!engine) throw new Error(`Unknown browser "${options.browser}". Use "chromium", "firefox" or "webkit".`);
|
|
67
|
+
const { headless, slowMo, args, channel, executablePath, timeout } = options;
|
|
68
|
+
this._browser = await engine.launch({ headless, slowMo, args, channel, executablePath, timeout });
|
|
69
|
+
const contextOptions = pickDefined(options, CONTEXT_FIELDS);
|
|
70
|
+
this._context = await this._browser.newContext({ viewport: options.viewport, acceptDownloads: true, ...contextOptions });
|
|
71
|
+
this._navigationTimeout = options.navigationTimeout;
|
|
72
|
+
this._page = await this._newPage();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async _newPage() {
|
|
76
|
+
const page = await this._context.newPage();
|
|
77
|
+
page.setDefaultNavigationTimeout(this._navigationTimeout);
|
|
78
|
+
this._watchDownloads(page);
|
|
79
|
+
return page;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Closes the browser and all its pages. */
|
|
83
|
+
async closeBrowser() {
|
|
84
|
+
try {
|
|
85
|
+
await this._browser?.close();
|
|
86
|
+
this._browser = this._context = this._page = null;
|
|
87
|
+
this._logger.info("Browser terminated successfully");
|
|
88
|
+
} catch (error) {
|
|
89
|
+
this._fail(error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Opens a new tab and makes it the current page. */
|
|
94
|
+
async openNewPage() {
|
|
95
|
+
this._requireBrowser();
|
|
96
|
+
this._page = await this._newPage();
|
|
97
|
+
return this._page;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Closes the current tab; the last remaining tab becomes current. */
|
|
101
|
+
async closeCurrentPage() {
|
|
102
|
+
if (!this._page) return;
|
|
103
|
+
await this._page.close();
|
|
104
|
+
this._page = this._context.pages().at(-1) ?? null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ─── Downloads & cookies ──────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
/** Creates the downloads folder and saves every download (on every tab) into it. */
|
|
110
|
+
async configureDownloadsFolder() {
|
|
111
|
+
this._requireBrowser();
|
|
112
|
+
fs.mkdirSync(this.downloadPath, { recursive: true });
|
|
113
|
+
this._context.on("page", (page) => this._watchDownloads(page));
|
|
114
|
+
this._context.pages().forEach((page) => this._watchDownloads(page));
|
|
115
|
+
this._logger.info(`Downloads folder configured: ${path.resolve(this.downloadPath)}`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
_watchDownloads(page) {
|
|
119
|
+
if (this._watched.has(page)) return;
|
|
120
|
+
this._watched.add(page);
|
|
121
|
+
page.on("download", (download) => this._saveDownload(download));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async _saveDownload(download) {
|
|
125
|
+
const target = path.join(this.downloadPath, download.suggestedFilename());
|
|
126
|
+
try {
|
|
127
|
+
await download.saveAs(target);
|
|
128
|
+
this._logger.info(`Download saved to ${target}`);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
this._logger.error(`Download failed: ${error.message}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async _setCookies(cookies) {
|
|
135
|
+
if (!cookies?.length) return;
|
|
136
|
+
await this._context.addCookies(cookies.map(normalizeCookie));
|
|
137
|
+
cookies.forEach((cookie) => this._logger.info(`"${cookie.name}" cookie configured successfully`));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ─── Navigation & interaction ─────────────────────────────────────────────
|
|
141
|
+
|
|
142
|
+
/** Navigates the current page to `url`. */
|
|
143
|
+
async goToPage(url, options) {
|
|
144
|
+
const page = this._activePage();
|
|
145
|
+
this._logger.info(`Navigating to ${url}`);
|
|
146
|
+
try {
|
|
147
|
+
return await page.goto(url, options);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
this._fail(error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Clicks the first visible element matching `selector` (waits `options.timeout` ms, default 5000). */
|
|
154
|
+
async click(selector, options) {
|
|
155
|
+
await this._require(selector, `Failed to click element: ${selector}`, options?.timeout);
|
|
156
|
+
await this._activePage().click(selector, options);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Fills an input, textarea or contenteditable matching `selector` (waits `options.timeout` ms, default 5000). */
|
|
160
|
+
async fill(selector, text, options) {
|
|
161
|
+
await this._require(selector, `Failed to fill element: ${selector}`, options?.timeout);
|
|
162
|
+
await this._activePage().fill(selector, text, options);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Returns the trimmed visible text of the first element matching `selector`. */
|
|
166
|
+
async getText(selector) {
|
|
167
|
+
await this._require(selector, `Failed to get text from element: ${selector}`);
|
|
168
|
+
return (await this._activePage().locator(selector).first().innerText()).trim();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Resolves true if a visible element matching `selector` appears within `timeout` ms. */
|
|
172
|
+
async elementExists(selector, timeout = 5000) {
|
|
173
|
+
const page = this._activePage();
|
|
174
|
+
try {
|
|
175
|
+
await page.locator(selector).first().waitFor({ state: "visible", timeout });
|
|
176
|
+
return true;
|
|
177
|
+
} catch {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Returns the absolute `href` of the first element matching `selector`. */
|
|
183
|
+
async getElementHrefLink(selector) {
|
|
184
|
+
await this._require(selector, `Failed to get href link from element: ${selector}`);
|
|
185
|
+
return this._activePage().locator(selector).first().evaluate((el) => el.href);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Returns the absolute `href` of every element matching `selector` (elements without one are skipped). */
|
|
189
|
+
async getElementsHrefLink(selector) {
|
|
190
|
+
const links = await this._activePage().locator(selector).evaluateAll((els) => els.map((el) => el.href));
|
|
191
|
+
return links.filter(Boolean);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Returns a Playwright Locator for the first element matching `selector`. */
|
|
195
|
+
async getElementBySelector(selector) {
|
|
196
|
+
await this._require(selector, `The element cannot be found: ${selector}`);
|
|
197
|
+
return this._activePage().locator(selector).first();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Returns a Playwright Locator for each element matching `selector`. */
|
|
201
|
+
async getElementsBySelector(selector) {
|
|
202
|
+
return this._activePage().locator(selector).all();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Resolves true if the element (a Locator) is disabled. */
|
|
206
|
+
async isElementDisabled(element) {
|
|
207
|
+
return element.isDisabled();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Scrolls to the bottom of the page, `distance` px every `delay` ms. */
|
|
211
|
+
async scrollDown(distance = 1000, delay = 1000) {
|
|
212
|
+
await this._activePage().evaluate(scrollToBottom, { distance, delay });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ─── Utilities ────────────────────────────────────────────────────────────
|
|
216
|
+
|
|
217
|
+
/** Saves a full-page screenshot to `<downloadPath>/<fileName>.<fileExt>` and returns its path. */
|
|
218
|
+
async screenshot(fileName, fileExt = "png", options = {}) {
|
|
219
|
+
const page = this._activePage();
|
|
220
|
+
fs.mkdirSync(this.downloadPath, { recursive: true });
|
|
221
|
+
const filePath = path.join(this.downloadPath, `${fileName}.${fileExt}`);
|
|
222
|
+
await page.screenshot({ path: filePath, fullPage: true, type: screenshotType(fileExt), ...options });
|
|
223
|
+
this._logger.info(`Screenshot saved to ${filePath}`);
|
|
224
|
+
return filePath;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Waits a random number of seconds between `start` and `limit`. */
|
|
228
|
+
async sleep(limit, start = 0) {
|
|
229
|
+
const seconds = Math.random() * (limit - start) + start;
|
|
230
|
+
return new Promise((resolve) => setTimeout(resolve, Math.floor(seconds * 1000)));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ─── Internals ────────────────────────────────────────────────────────────
|
|
234
|
+
|
|
235
|
+
_activePage() {
|
|
236
|
+
if (!this._page) throw new Error("Browser is not open. Call openBrowser() first.");
|
|
237
|
+
return this._page;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
_requireBrowser() {
|
|
241
|
+
if (!this._context) throw new Error("Browser is not open. Call openBrowser() first.");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async _require(selector, message, timeout = 5000) {
|
|
245
|
+
if (!(await this.elementExists(selector, timeout))) throw new Error(message);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
_fail(error) {
|
|
249
|
+
this._logger.error(error.message);
|
|
250
|
+
throw error;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function normalizeOpenOptions(cookiesOrOptions, headless, slowMo) {
|
|
255
|
+
const legacy = cookiesOrOptions === null || Array.isArray(cookiesOrOptions);
|
|
256
|
+
const options = legacy ? { cookies: cookiesOrOptions, headless, slowMo } : { ...cookiesOrOptions };
|
|
257
|
+
return {
|
|
258
|
+
browser: "chromium",
|
|
259
|
+
slowMo: 30,
|
|
260
|
+
viewport: DEFAULT_VIEWPORT,
|
|
261
|
+
navigationTimeout: DEFAULT_NAVIGATION_TIMEOUT,
|
|
262
|
+
cookies: null,
|
|
263
|
+
...options,
|
|
264
|
+
headless: options.headless !== false, // true, undefined and the legacy "new" all mean headless
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function normalizeCookie(cookie) {
|
|
269
|
+
const entries = COOKIE_FIELDS.filter((key) => cookie[key] !== undefined).map((key) => [key, cookie[key]]);
|
|
270
|
+
const clean = Object.fromEntries(entries);
|
|
271
|
+
if (clean.expires === undefined && cookie.expirationDate) clean.expires = cookie.expirationDate;
|
|
272
|
+
if (clean.sameSite !== undefined) clean.sameSite = SAME_SITE[String(clean.sameSite).toLowerCase()];
|
|
273
|
+
if (clean.sameSite === undefined) delete clean.sameSite;
|
|
274
|
+
if (!clean.url && !clean.path) clean.path = "/";
|
|
275
|
+
return clean;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function pickDefined(source, keys) {
|
|
279
|
+
return Object.fromEntries(keys.filter((key) => source[key] !== undefined).map((key) => [key, source[key]]));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function screenshotType(fileExt) {
|
|
283
|
+
return /^jpe?g$/i.test(fileExt) ? "jpeg" : "png";
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Runs inside the browser — must not reference anything outside its own scope.
|
|
287
|
+
function scrollToBottom({ distance, delay }) {
|
|
288
|
+
return new Promise((resolve) => {
|
|
289
|
+
let total = 0;
|
|
290
|
+
const timer = setInterval(() => {
|
|
291
|
+
window.scrollBy(0, distance);
|
|
292
|
+
total += distance;
|
|
293
|
+
if (total >= document.body.scrollHeight) {
|
|
294
|
+
clearInterval(timer);
|
|
295
|
+
resolve();
|
|
296
|
+
}
|
|
297
|
+
}, delay);
|
|
298
|
+
});
|
|
299
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { Browser, BrowserContext, Locator, Page, PageScreenshotOptions, Response } from "playwright";
|
|
2
|
+
|
|
3
|
+
export { chromium, firefox, webkit, devices } from "playwright";
|
|
4
|
+
|
|
5
|
+
export type BrowserName = "chromium" | "firefox" | "webkit";
|
|
6
|
+
export type LogLevel = "debug" | "info" | "warn" | "error";
|
|
7
|
+
|
|
8
|
+
export interface CookieInput {
|
|
9
|
+
name: string;
|
|
10
|
+
value: string;
|
|
11
|
+
/** Either `url`, or `domain` (+ optional `path`, defaults to "/") is required. */
|
|
12
|
+
url?: string;
|
|
13
|
+
domain?: string;
|
|
14
|
+
path?: string;
|
|
15
|
+
/** Unix time in seconds. `expirationDate` (Chrome export format) is accepted too. */
|
|
16
|
+
expires?: number;
|
|
17
|
+
expirationDate?: number;
|
|
18
|
+
httpOnly?: boolean;
|
|
19
|
+
secure?: boolean;
|
|
20
|
+
/** "Strict" | "Lax" | "None"; lowercase and Chrome's "no_restriction" are accepted. */
|
|
21
|
+
sameSite?: string;
|
|
22
|
+
[extra: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Playwright's storage state, e.g. what `context.storageState()` returns. Passed to Playwright as-is:
|
|
27
|
+
* cookies need `url`, or `domain` + `path`, and `sameSite` must be "Strict" | "Lax" | "None".
|
|
28
|
+
*/
|
|
29
|
+
export interface StorageState {
|
|
30
|
+
cookies: Array<{
|
|
31
|
+
name: string;
|
|
32
|
+
value: string;
|
|
33
|
+
url?: string;
|
|
34
|
+
domain?: string;
|
|
35
|
+
path?: string;
|
|
36
|
+
/** Unix time in seconds. */
|
|
37
|
+
expires?: number;
|
|
38
|
+
httpOnly?: boolean;
|
|
39
|
+
secure?: boolean;
|
|
40
|
+
sameSite?: "Strict" | "Lax" | "None";
|
|
41
|
+
}>;
|
|
42
|
+
origins: Array<{ origin: string; localStorage: Array<{ name: string; value: string }> }>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface OpenBrowserOptions {
|
|
46
|
+
/** Which engine to launch. Default: "chromium". */
|
|
47
|
+
browser?: BrowserName;
|
|
48
|
+
/** Default: true. The legacy value "new" also means headless. */
|
|
49
|
+
headless?: boolean | "new";
|
|
50
|
+
/** Milliseconds to slow every Playwright action by. Default: 30. */
|
|
51
|
+
slowMo?: number;
|
|
52
|
+
/** Cookies to set before the first navigation. */
|
|
53
|
+
cookies?: CookieInput[] | null;
|
|
54
|
+
/** Default: { width: 1920, height: 1080 }. Pass null to disable the fixed viewport. */
|
|
55
|
+
viewport?: { width: number; height: number } | null;
|
|
56
|
+
/** Default navigation timeout in ms. Default: 60000. Use 0 to disable. */
|
|
57
|
+
navigationTimeout?: number;
|
|
58
|
+
/** Extra command-line arguments for the browser executable. */
|
|
59
|
+
args?: string[];
|
|
60
|
+
/** Browser distribution channel, e.g. "chrome" or "msedge" to use an installed browser. */
|
|
61
|
+
channel?: string;
|
|
62
|
+
/** Path to a browser executable instead of the one Playwright manages. */
|
|
63
|
+
executablePath?: string;
|
|
64
|
+
/** Launch timeout in ms. */
|
|
65
|
+
timeout?: number;
|
|
66
|
+
/** Resume a saved session: a path to a JSON file or the object from `context.storageState()`. */
|
|
67
|
+
storageState?: string | StorageState;
|
|
68
|
+
/** User agent for the context. Default: the browser's own. */
|
|
69
|
+
userAgent?: string;
|
|
70
|
+
/** Locale for the context, e.g. "en-US". Default: the system locale. */
|
|
71
|
+
locale?: string;
|
|
72
|
+
/** Time zone for the context, e.g. "Asia/Jerusalem". Default: the system time zone. */
|
|
73
|
+
timezoneId?: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface BrowserHandlerOptions {
|
|
77
|
+
/** Minimum log level of the built-in logger-standard logger. Default: "info". */
|
|
78
|
+
logLevel?: LogLevel;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export default class BrowserHandler {
|
|
82
|
+
constructor(downloadPath?: string, options?: BrowserHandlerOptions);
|
|
83
|
+
|
|
84
|
+
/** Folder where screenshots and downloads are saved. */
|
|
85
|
+
downloadPath: string;
|
|
86
|
+
|
|
87
|
+
readonly browser: Browser | null;
|
|
88
|
+
readonly context: BrowserContext | null;
|
|
89
|
+
readonly page: Page | null;
|
|
90
|
+
|
|
91
|
+
openBrowser(options?: OpenBrowserOptions | null): Promise<void>;
|
|
92
|
+
openBrowser(cookies: CookieInput[] | null, headless?: boolean | "new", slowMo?: number): Promise<void>;
|
|
93
|
+
closeBrowser(): Promise<void>;
|
|
94
|
+
openNewPage(): Promise<Page>;
|
|
95
|
+
closeCurrentPage(): Promise<void>;
|
|
96
|
+
configureDownloadsFolder(): Promise<void>;
|
|
97
|
+
|
|
98
|
+
goToPage(url: string, options?: Parameters<Page["goto"]>[1]): Promise<Response | null>;
|
|
99
|
+
click(selector: string, options?: Parameters<Page["click"]>[1]): Promise<void>;
|
|
100
|
+
fill(selector: string, text: string, options?: Parameters<Page["fill"]>[2]): Promise<void>;
|
|
101
|
+
getText(selector: string): Promise<string>;
|
|
102
|
+
elementExists(selector: string, timeout?: number): Promise<boolean>;
|
|
103
|
+
getElementHrefLink(selector: string): Promise<string>;
|
|
104
|
+
getElementsHrefLink(selector: string): Promise<string[]>;
|
|
105
|
+
getElementBySelector(selector: string): Promise<Locator>;
|
|
106
|
+
getElementsBySelector(selector: string): Promise<Locator[]>;
|
|
107
|
+
isElementDisabled(element: Locator): Promise<boolean>;
|
|
108
|
+
scrollDown(distance?: number, delay?: number): Promise<void>;
|
|
109
|
+
|
|
110
|
+
screenshot(fileName: string, fileExt?: "png" | "jpg" | "jpeg", options?: PageScreenshotOptions): Promise<string>;
|
|
111
|
+
sleep(limit: number, start?: number): Promise<void>;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export { BrowserHandler };
|