Playwright + TS · Lesson 23 of 36

0/36 done

Module 23: Browser Events & File Handling

23. Listening to Browser Events & Managing File Workflows

17 minlesson

Try it yourself

Implement validateDownloadedFileSize:

  1. Accept sizeBytes and optional minBytes (default 1024).
  2. Return true if sizeBytes is at least minBytes.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

1. Intercepting Console Errors

A test can pass its UI assertions while the browser console throws critical JavaScript uncaught exceptions:

typescript
test("page should load with zero console errors", async ({ page }) => {
  const errors: string[] = [];
  page.on("pageerror", (exception) => {
    errors.push(exception.message);
  });

  await page.goto("https://targetqa.com");
  expect(errors).toHaveLength(0);
});

2. Handling File Chooser & Custom Upload Buttons

If a file input is hidden behind a stylized button:

typescript
// Start waiting for file chooser before clicking the trigger:
const fileChooserPromise = page.waitForEvent("filechooser");
await page.getByRole("button", { name: "Select Document" }).click();
const fileChooser = await fileChooserPromise;

// Attach file:
await fileChooser.setFiles("fixtures/sample-contract.pdf");

3. File Downloads & Verification

typescript
import fs from "fs";

test("download invoice pdf and verify file exists", async ({ page }) => {
  const downloadPromise = page.waitForEvent("download");
  await page.getByRole("button", { name: "Download PDF" }).click();
  const download = await downloadPromise;

  const savePath = `test-results/${download.suggestedFilename()}`;
  await download.saveAs(savePath);

  // Assert file exists on disk and is non-empty:
  expect(fs.existsSync(savePath)).toBeTruthy();
  expect(fs.statSync(savePath).size).toBeGreaterThan(100);
});

Key Takeaways & Walkthrough Summary

A comprehensive automated test does more than click buttons; it also verifies that no console errors occurred and validates downloaded files. In this lesson, we will learn how to listen to browser events, intercept console logs, handle custom file uploaders, and verify downloaded documents. Let's get started!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Where are temporary downloads stored before calling saveAs?

Playwright stores downloads in a temporary isolated cache directory. If you don't call saveAs(), the file is automatically deleted when the BrowserContext closes.

Can Playwright intercept WebSocket frames?

Yes! You can use page.on('websocket', ws => { ws.on('framereceived', ...); }) to inspect real-time communications.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

TypeScript
Skip