webstack-screenshot
Version:
📸网站截图 API | Website Screenshot API
72 lines (68 loc) • 1.92 kB
JavaScript
;
const DEFAULT_VIEWPORT = {
width: 1920,
height: 1080
};
class Screenshot {
static instance;
constructor() {
console.log("Browser singleton instance created");
}
static getInstance() {
if (!Screenshot.instance) {
Screenshot.instance = new Screenshot();
}
return Screenshot.instance;
}
async getScreenshot(page, options) {
await this.setViewport(page, options);
await page.goto(options.url, {
timeout: options.timeout ?? 3e4,
waitUntil: options.waitUntil ?? "load"
});
const opts = this.parse(options);
const buffer = await page.screenshot(opts);
return buffer;
}
async setViewport(page, options) {
const viewport = { ...DEFAULT_VIEWPORT, ...options.viewport, isMobile: options.isMobile ?? false };
if (typeof options.viewport === "string") {
const v = this.parseViewport(options.viewport);
Object.assign(viewport, v);
}
await page.setViewport(viewport);
}
parse(options) {
const { quality = 80, type = "jpeg", encoding = "binary", fullPage = false, clip } = options;
const opts = {
// Image quality between 0-100, ignored if the image type is png
type,
quality,
// Screenshot of the full page
fullPage,
encoding
};
if (typeof clip === "string") {
opts.clip = this.parseClip(clip);
}
if (typeof clip === "object") {
opts.clip = clip;
}
return opts;
}
/// --- utils
parseViewport(viewportString) {
const [width, height] = viewportString.split("x").map((str) => +str.trim());
if (width && height) {
return { width, height };
}
}
parseClip(clip) {
const [x, y, width, height] = clip.split(",").map((part) => +part.trim());
if (x && y && width && height) {
return { x, y, width, height };
}
}
}
exports.DEFAULT_VIEWPORT = DEFAULT_VIEWPORT;
exports.Screenshot = Screenshot;