Playwright Advanced Page Operations
This chapter introduces Playwright advanced page operations, which are closer to real testing needs, covering **waiting mechanisms, form handling, and dialog boxes** and other advanced features.
* * *
## Waiting Mechanisms
One of Playwright's biggest advantages is **intelligent waiting (auto-waiting)**: most operations (such as `click`, `fill`) automatically wait for elements to be visible and actionable. However, in complex scenarios, manual control of waiting is still required.
### 1. Implicit Waiting (Auto-waiting)
Playwright's built-in waiting mechanism:
* **Element visible**
* **Clickable / Interactive**
* **Page load complete**
## Example
await page.click('#submit');// Automatically waits for the button to be visible and clickable
### 2. Explicit Waiting
Explicitly call waiting methods, such as waiting for a selector, text, or request.
## Example
await page.waitForSelector('#result',{ state:'visible'});
Common `state` values:
* `'attached'` β Element appears in the DOM
* `'visible'` β Element is visible on the page
* `'hidden'` β Element is hidden
* `'detached'` β Element is removed
### 3. Waiting for Element to Appear / Disappear
// Wait for element to appear await page.waitForSelector('#loading', { state: 'visible' });// Wait for element to disappear await page.waitForSelector('#loading', { state: 'hidden' });
### 4. Waiting for Network Request Completion
Wait for a specific request to complete, commonly used for AJAX requests or API calls.
// Wait for a request with the specified URL to complete await page.waitForResponse(response => response.url().includes('/api/login') && response.status() === 200);
### 5. Custom Waiting Conditions
Execute custom waiting logic through `page.waitForFunction`.
// Wait for the counter on the page to reach 10 await page.waitForFunction(() => { return document.querySelector('#count').innerText === '10';});
* * *
## Form Handling
Forms are the most common interaction scenarios in testing. Playwright provides rich APIs to manipulate form controls.
### 1. Input Field Operations
await page.fill('#username', 'admin'); // Clear and input await page.type('#search', 'Playwright', { delay: 100 }); // Simulate typing character by character
### 2. Dropdown Menu Selection
// By value await page.selectOption('#country', 'china');// By label text await page.selectOption('#country', { label: 'United States' });// By index await page.selectOption('#country', { index: 2 });
### 3. Checkboxes and Radio Buttons
// Check checkbox await page.check('#agree');// Uncheck await page.uncheck('#subscribe');// Click radio button await page.check('input');
### 4. File Upload
// Upload file directly await page.setInputFiles('#upload', 'example.png');// Upload multiple files await page.setInputFiles('#upload', ['a.png', 'b.png']);// Clear files await page.setInputFiles('#upload', []);
### 5. Form Submission
There are two ways to submit a form:
* Click the submit button
* Directly trigger the form submission event
await page.click('button');// Or await page.press('#form input', 'Enter');
* * *
## Dialogs and Pop-ups
Playwright can capture and handle **browser native dialogs** (alert, confirm, prompt), as well as custom modal boxes.
### 1. Alert Handling
page.once('dialog', async dialog => { console.log(dialog.message()); // Print dialog content await dialog.accept(); // Click "OK"}); await page.click('#show-alert');
### 2. Confirm Handling
page.once('dialog', async dialog => { console.log(dialog.message()); await dialog.dismiss(); // Click "Cancel"}); await page.click('#show-confirm');
### 3. Prompt Handling
page.once('dialog', async dialog => { console.log(dialog.message()); await dialog.accept('Playwright'); // Enter content and confirm}); await page.click('#show-prompt');
### 4. Custom Modal Boxes
Custom modal boxes (such as Bootstrap / Ant Design) are essentially ordinary DOM elements and can be closed or input using **locating + interacting** methods.
await page.click('#open-modal'); await page.fill('.modal input', 'Test User'); await page.click('.modal button.confirm');
* * *
## Practical Case β Automated Registration Form Testing
The following example combines the use of **waiting mechanisms, form operations, file upload, and dialog handling**.
## Example
// register-test.js
const{ chromium }= require('playwright');
(async ()=>{
const browser = await chromium.launch({ headless:false, slowMo:500});
const context = await browser.newContext();
const page = await context.newPage();
// 1. Open registration page
await page.goto('https://example.com/register',{ waitUntil:'domcontentloaded'});
// 2. Wait for form to appear
await page.waitForSelector('#register-form',{ state:'visible'});
// 3. Enter basic information
await page.fill('#username','testuser');
await page.fill('#email','test@example.com');
await page.fill('#password','Password123');
// 4. Select country from dropdown
await page.selectOption('#country',{ label:'China'});
// 5. Check terms agreement
await page.check('#agree');
// 6. Upload avatar
await page.setInputFiles('#avatar','avatar.png');
// 7. Click submit
page.once('dialog', async dialog =>{
console.log('Dialog content:', dialog.message());
await dialog.accept();// Click OK
});
await page.click('button');
// 8. Wait for redirect after submission
await page.waitForLoadState('networkidle');
// 9. Assert result (whether it contains welcome text)
const successText = await page.textContent('.welcome-message');
console.log('Registration result:', successText);
// 10. Take screenshot
await page.screenshot({ path:'register-success.png'});
await browser.close();
})();
Running results:
* Automatically fill in form, select country, upload avatar
* Automatically handle dialogs
* Take screenshot and verify welcome message after submission
* * *
## Complete API
The following is a summary of commonly used APIs for **page navigation, waiting, forms, interactions, and dialogs**:
| Category | Method / Property | Description |
| --- | --- | --- |
| Page Navigation | `page.goto(url[, options])` | Open page |
| | `page.reload()` | Refresh page |
| | `page.goBack()` | Go back |
| | `page.goForward()` | Go forward |
| | `page.waitForLoadState([state, options])` | Wait for load to complete |
| Waiting Mechanisms | `page.waitForSelector(selector[, options])` | Wait for element to appear/disappear |
| | `page.waitForResponse(fn[, options])` | Wait for specified request response |
| | `page.waitForFunction(pageFn[, arg, options])` | Custom waiting condition |
| Element Locating | `page.locator(selector)` | Universal locator |
| | `page.getByRole(role, options)` | Locate by role |
| | `page.getByText(text)` | Locate by text |
| | `page.getByPlaceholder(text)` | Input box placeholder |
| | `page.getByLabel(text)` | Form label |
| Form Operations | `page.fill(selector, value)` | Input field (clear then fill) |
| | `page.type(selector, text[, options])` | Simulate typing character by character |
| | `page.press(selector, key)` | Press key on element |
| | `page.selectOption(selector, values)` | Dropdown menu selection |
| | `page.check(selector[, options])` | Check checkbox/radio button |
| | `page.uncheck(selector[, options])` | Uncheck |
| | `page.setInputFiles(selector, files)` | File upload |
| Basic Interactions | `page.click(selector[, options])` | Click element |
| | `page.dblclick(selector[, options])` | Double-click |
| | `page.hover(selector[, options])` | Hover |
| | `page.mouse.move(x, y)` | Mouse move |
| | `page.mouse.click(x, y[, options])` | Mouse click |
| | `page.dragAndDrop(src, dest[, options])` | Drag and drop element |
| Dialog Handling | `page.on('dialog', handler)` | Listen for dialog events |
| | `dialog.message()` | Get dialog text |
| | `dialog.accept()` | Confirm (can input content) |
| | `dialog.dismiss()` | Cancel |
| Screenshots and Assertions | `page.screenshot({ path })` | Take screenshot and save |
| | `page.textContent(selector)` | Get text content |
| | `expect(locator).toHaveText(text)` | Assert text (requires [@playwright](https://github.com/playwright "@playwright")/test) |
YouTip