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.
![](/_next/image?url=https%3A%2F%2Fimages.ctfassets.net%2Fzi1ovlormku8%2F6j1HOSEpdKNVzJ0gN8Q2RI%2F6680737bcf153a8a4f53aa02d787cc70%2Fchristian-wiediger-8nXKXYdO-Wk-unsplash.jpg&w=3840&q=75)
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.
![playwright06.png](/_next/image?url=https%3A%2F%2Fimages.ctfassets.net%2Fzi1ovlormku8%2F6IDFSiJKtUiKGrRFpscUki%2F64984734fc022476578b4d57658acc9a%2Fplaywright06.png&w=3840&q=75)
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
![playwright07.png](/_next/image?url=https%3A%2F%2Fimages.ctfassets.net%2Fzi1ovlormku8%2F5pSFQbgeVffks1hSL081Yz%2F79354ebfc88c409994938fffb8b241af%2Fplaywright07.png&w=3840&q=75)
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.