Playwright can sign in to an authorized web app, capture a page, and repeat the task on a schedule using your operating system’s scheduler or a CI runner. You’ll need Node.js, access credentials for a test account, and permission to automate the app; keep passwords and screenshots out of public logs and repositories.
What You’ll Need
- A computer or runner with Node.js installed and network access to the app.
- Permission to automate the app and a dedicated account suitable for screenshots. Avoid personal accounts and production actions.
- The app’s sign-in URL and the URL of the page to capture, plus any required second-factor or access procedure.
- A private place for credentials, such as environment variables supplied by your scheduler or CI secret store.
- A folder with enough storage for screenshots and a plan to limit retention.
Step-by-Step
- Create a project. In a terminal, make a directory for the job, change into it, and run
npm init -y. Install Playwright withnpm install playwright. Install a browser supported by the installed package usingnpx playwright install chromium. On Linux runners, usenpx playwright install --with-deps chromiumif browser system dependencies are missing. - Choose a predictable login method. First check whether the app provides a dedicated test login or supported authentication flow. Do not try to bypass CAPTCHA, multi-factor authentication, access controls, or bot protections. If interactive sign-in is required, coordinate with the app owner for an approved automation approach. Avoid storing long-lived session files in source control.
- Provide settings securely. Configure environment variables named
APP_URL,LOGIN_URL,APP_USER, andAPP_PASSWORD. Set these in your shell for a local test, or in the scheduler’s protected environment or secret settings. Do not put real credentials directly in JavaScript, command-line arguments, screenshots, or logs. Add output folders and any local secret file to.gitignore. - Write the capture script. Save the following as
screenshot.js. Replace the example selectors with selectors that match your app. Prefer stable labels, roles, or test IDs over fragile CSS paths.
const { chromium } = require('playwright');
async function main() {
const { APP_URL, LOGIN_URL, APP_USER, APP_PASSWORD } = process.env;
if (!APP_URL || !LOGIN_URL || !APP_USER || !APP_PASSWORD) {
throw new Error('Set APP_URL, LOGIN_URL, APP_USER, and APP_PASSWORD');
}
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
try {
await page.goto(LOGIN_URL, { waitUntil: 'domcontentloaded' });
await page.getByLabel('Email').fill(APP_USER);
await page.getByLabel('Password').fill(APP_PASSWORD);
await page.getByRole('button', { name: 'Sign in' }).click();
// Replace this with a reliable post-login condition for your app.
await page.getByRole('heading', { name: 'Dashboard' }).waitFor();
await page.goto(APP_URL, { waitUntil: 'domcontentloaded' });
await page.getByRole('main').waitFor();
await page.screenshot({ path: 'screenshots/app.png', fullPage: true });
} finally {
await browser.close();
}
}
main().catch(error => {
console.error('Screenshot job failed:', error.message);
process.exitCode = 1;
});
- Prepare the output folder and selectors. Create the
screenshotsdirectory before running the script; Playwright does not create missing parent directories for a screenshot path. Update the field labels, button name, post-login heading, and main-content locator to match the page. A post-login check is important: it prevents capturing a sign-in page after an unsuccessful login. - Run it manually first. Set the four environment variables in your terminal, then run
node screenshot.js. Check that the screenshot shows the intended page and that no password or private information is visible. The script uses a fixed viewport and full-page capture for more consistent output. If the app renders content after loading, wait for a specific element or an appropriate response rather than adding a long arbitrary sleep. - Schedule the script. For a Linux or macOS machine, use the user’s crontab with
crontab -eand add a line such as0 8 * * * cd /absolute/path/to/project && /usr/bin/node screenshot.jsto run daily at 8:00 according to that machine’s time zone. Configure the job’s environment securely; cron may not inherit your interactive shell variables. For Windows, create a task in Task Scheduler that startsnode, uses the project directory as the working folder, and runs at the desired time. Store secrets through an approved protected mechanism rather than in a broadly readable task file. - Check runs and maintain the job. Review the scheduler’s status or logs after the first scheduled run. Confirm the output timestamp, image contents, and file permissions. Set a retention policy or periodically delete old captures, especially if pages contain personal or business data. Monitor failures and update selectors when the app’s interface changes.
Common Mistakes
- Using incorrect selectors: A label or button name may differ from the example. Inspect the page and use its accessible name, or ask the app team for stable test IDs.
- Assuming navigation means login succeeded: Some apps remain on the login page or show an error without a useful URL change. Wait for a dashboard element and handle authentication failures explicitly.
- Scheduling with the wrong environment: Cron and Task Scheduler may use a different working directory, Node path, user, or environment from your terminal. Use absolute paths and test under the same account that will run the job.
- Ignoring two-factor requirements: Repeatedly automating a flow that requires an interactive code is unreliable. Use only an approved test account and authentication method; never circumvent the app’s controls.
- Leaving sensitive captures unprotected: Screenshots can expose account data even when passwords are hidden. Restrict access, use private storage, and remove files when they are no longer needed.
Tips
- Run headed during initial debugging by changing
chromium.launch({ headless: true })tochromium.launch({ headless: false })on a machine with a display. Restore headless mode for most scheduled jobs. - Use a separate account with the minimum access needed and, where possible, a page with non-sensitive sample data.
- Capture only the necessary page region if full-page screenshots include unrelated or confidential content. Playwright supports element screenshots with a locator’s
screenshot()method. - Use a unique filename containing a date or timestamp if you need a history; otherwise the example overwrites the previous image. Make sure your retention policy still applies.
- Keep browser and Playwright versions consistent across runs, especially in CI, and install the browser after updating the package.
Troubleshooting
If the browser does not launch, run npx playwright install chromium again and check that the scheduled user can access the installed browser and project files. On Linux, missing shared libraries may require npx playwright install --with-deps chromium or help from the machine administrator.
If the job reports missing environment variables, verify that each variable is configured for the scheduler’s actual user and process. Do not print secret values to diagnose this; log whether a value is present instead. If login times out, check the sign-in URL, network access, account status, and selectors. If an extra authentication prompt appears, stop and arrange an approved workflow with the app owner.
If the image is blank or incomplete, wait for a meaningful page element, check for application errors, and confirm the viewport and destination URL. For dynamic charts or animations, wait for the specific chart or content to become ready. If a screenshot fails because its folder is missing, create the folder before capture. If scheduled runs overlap, use a scheduler setting or lock so only one job writes the same output at a time.
Frequently Asked Questions
Can Playwright take screenshots after signing in?
Yes. The script can fill a permitted login form, verify that the authenticated page loaded, and then capture it. Authentication requirements vary, so use an approved flow.
Where should I put the password?
Use protected environment variables or your scheduler or CI platform’s secret store. Do not commit credentials or print them in logs.
Can I reuse a saved login session?
Playwright supports saved browser storage state, but it contains authentication data. Store it as a secret, restrict access, set an expiry or refresh process, and never commit it to a repository.
How do I make screenshots run at a particular time?
Schedule the Node command with cron on Linux or macOS, Task Scheduler on Windows, or a CI scheduler. Check the machine or runner’s time zone and ensure secrets are available to the job.
Why does the screenshot show the login page?
The login may have failed, a selector may target the wrong control, or the app may need more time to render. Verify the post-login condition and check the account and app’s approved authentication process.
How can I capture only one section?
Locate the element you want and call await locator.screenshot({ path: 'screenshots/section.png' }) after it is visible. This can reduce unnecessary exposure in the image.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- How to Use an iMessage Group Chat
- Import Data From the Web Into Microsoft Excel
- Record Video From Your iPhone on a Mac
- How to Copy Text from a Video on iPhone
- Epson XP-330 Driver Issues: How to Fix Them
- How to Sync Music to iPhone 11: A Step-by-Step Guide