Skip to content

Commit 3e61f7c

Browse files
add pupeteer resapwn
1 parent 585b251 commit 3e61f7c

1 file changed

Lines changed: 33 additions & 24 deletions

File tree

testing/testing-screenshot/index.ts

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,6 @@ interface ScreenshotOptions {
88
};
99
}
1010

11-
export async function screenshot({ htmlcss, viewport }: ScreenshotOptions) {
12-
const worker = new Worker({});
13-
await worker.launch();
14-
const buffer = worker.screenshot({ htmlcss, viewport });
15-
await worker.terminate();
16-
return buffer;
17-
}
18-
1911
export class Worker {
2012
private browser: Browser;
2113
private page: Page;
@@ -46,30 +38,47 @@ export class Worker {
4638
}
4739

4840
async screenshot({ htmlcss, viewport }: ScreenshotOptions) {
49-
// check if page is available (try to avoid TargetClosedError)
50-
if (!this.page || this.page.isClosed()) {
41+
try {
42+
if (!this.browser || !this.page || this.page.isClosed()) {
43+
await this.relaunch();
44+
}
45+
await this.page.setViewport(viewport);
46+
await this.page.setContent(htmlcss, { waitUntil: "networkidle0" });
47+
const buffer = await this.page.screenshot({
48+
type: "png",
49+
// support transparency
50+
omitBackground: true,
51+
});
52+
return buffer;
53+
} catch (error) {
54+
console.log(`Failed to take screenshot: ${error.message}`);
5155
await this.relaunch();
56+
// After relaunch, retry taking screenshot or rethrow the error
57+
return this.screenshot({ htmlcss, viewport });
5258
}
53-
54-
this.page.setViewport(viewport);
55-
await this.page.setContent(htmlcss, { waitUntil: "networkidle0" });
56-
const buffer = await this.page.screenshot({
57-
type: "png",
58-
// support transparency
59-
omitBackground: true,
60-
});
61-
return buffer;
6259
}
6360

6461
async close() {
65-
try {
66-
await this.browser.close();
67-
} catch (e) {}
68-
this.browser = null;
69-
this.page = null;
62+
if (this.browser) {
63+
try {
64+
await this.browser.close();
65+
} catch (e) {
66+
console.log(`Failed to close browser: ${e.message}`);
67+
}
68+
this.browser = null;
69+
this.page = null;
70+
}
7071
}
7172

7273
terminate() {
7374
this.close();
7475
}
7576
}
77+
78+
export async function screenshot(options: ScreenshotOptions) {
79+
const worker = new Worker({});
80+
await worker.launch();
81+
const buffer = await worker.screenshot(options);
82+
await worker.terminate();
83+
return buffer;
84+
}

0 commit comments

Comments
 (0)