[Playwright Interview question #7]: Cách handle popup và dialog box trong Playwright?
Câu hỏi phỏng vấn #7: Cách handle popup và dialog box trong Playwright?
Trả lời mẫu:
Playwright hỗ trợ handle các loại dialog boxes khác nhau:
1. Alert, Confirm, Prompt dialogs:
// Setup dialog handler trước khi trigger
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept(); // hoặc dialog.dismiss()
});
// Trigger dialog
await page.locator('#show-alert').click();
2. Handle prompt với input value:
page.on('dialog', async dialog => {
if (dialog.type() === 'prompt') {
await dialog.accept('My answer');
}
});
3. One-time dialog handler:
page.once('dialog', dialog => dialog.dismiss());
await page.locator('#show-confirm').click();
4. Before unload dialog:
// Auto dismiss by default
await page.close({ runBeforeUnload: true });
5. File chooser dialog:
const [fileChooser] = await Promise.all([
page.waitForEvent('filechooser'),
page.locator('#upload-button').click()
]);
await fileChooser.setFiles('path/to/file.pdf');
💡 Tips:
- Dialog handler phải setup TRƯỚC khi trigger dialog
- Unhandled dialog sẽ auto-dismiss
- Dùng
page.once()
cho one-time handling - File upload có thể dùng
input.setInputFiles()
trực tiếp
Lời Kết
Playwright đang trở thành một trong những automation frameworks phổ biến nhất cho web testing. Thông qua series này, hy vọng bạn sẽ:
- Nắm vững kiến thức từ cơ bản đến nâng cao
- Tự tin trong các buổi phỏng vấn
- Áp dụng hiệu quả vào dự án thực tế
- Trở thành một phần của cộng đồng Playwright Việt Nam năng động
📚 Bắt đầu hành trình của bạn với: Bài 1: Playwright vs Selenium
💬 Có câu hỏi? Tham gia group Facebook của chúng mình!
⭐ Theo dõi series để không bỏ lỡ bài viết mới!
All Rights Reserved