Playwright did not come up with anything as far as creating a Typescript sample. This time, I would like to add it as soon as possible.
Content Update
Please check the latest information on the following page
The previous article is as follows
Install Playwright
For your project, install playwright as follows
npm install playwright@latest
Then create a file named routes/screenshot.ts using the following code
import { Request, Response } from "express";
import { chromium } from "playwright";
export const screenshot = async (req: Request, res: Response) => {
const urlParam = req.query.url as string;
if (!urlParam) {
return res.status(400).json({ error: "URL parameter is required" });
}
console.log(`Processing screenshot for URL: ${urlParam}`);
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(urlParam);
await page.waitForTimeout(2000);
const screenshot = await page.screenshot();
res.setHeader("Content-Type", "image/png");
res.send(screenshot);
await browser.close();
console.log("Screenshot taken");
};
Now screenshot.ts is ready. Next, modify the app.ts file. First, add the following line as import
import { screenshot } from "./routes/screenshot";
Then add a second endpoint, this time under hello.
app.get("/api/hello", hello);
app.get("/api/screenshot", screenshot);
Now screenshot will work as an API other than hello. Actually run it with npm run start. After execution, access http://localhost:3000/api/screenshot?url=https://haramizu.com and you will see the screenshot as follows.
The screenshot was taken at a size of 1280 x 720 after accessing the site with a browser.
Change the size of the screen to be acquired
The above is a very simple screenshot taking mechanism. It is a form of taking a screenshot, waiting a little time to display it. So what if we want to change the screen size? You can specify the screen size with setViewPortSize as shown below.
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setViewportSize({ width: 1600, height: 1200 });
await page.goto(urlParam);
await page.waitForTimeout(2000);
The screenshots obtained with this are as follows
Summary
Since the purpose of using Playwright this time is to obtain screenshots, we will use this as the basis for the tool. The tool itself is a useful tool that allows you to set up scenarios and automate testing of browser behavior. If you are interested, please feel free to experiment with it.