🌐 Network Handling - HTTP Configuration in Playwright
The Big Picture: Your Browser’s Secret Agent Kit
Imagine you’re a secret agent going on a mission. Before you leave, you need:
- 🎫 A badge to get into secure buildings (HTTP credentials)
- 📦 Special packages to deliver messages (Extra HTTP headers)
- 🕵️ A disguise that works even with broken ID scanners (Ignore HTTPS errors)
- 📵 A way to practice when there’s no signal (Offline mode)
Playwright gives your browser all these spy tools! Let’s discover each one.
🎫 HTTP Credentials: Your Badge to Get In
What’s This?
Some websites have a special lock. Before you even see the page, a little box pops up asking for a username and password. This is called “HTTP Authentication.”
Real Life Example:
- A secret clubhouse has a guard at the door
- The guard asks: “What’s the password?”
- Only if you say the right words, you can enter
How Playwright Does It
const context = await browser.newContext({
httpCredentials: {
username: 'agent007',
password: 'secretPassword123'
}
});
What happens:
- Browser tries to visit the protected page
- Server asks: “Who are you?”
- Playwright automatically says: “I’m agent007!”
- Server says: “Come in!”
When Do You Need This?
- Testing staging/development websites
- Accessing password-protected admin panels
- Working with APIs that need basic authentication
graph TD A["🌐 Browser visits page"] --> B{🔐 Protected?} B -->|Yes| C["Server asks for credentials"] C --> D["Playwright sends username/password"] D --> E["✅ Access granted!"] B -->|No| F["✅ Page loads normally"]
📦 Extra HTTP Headers: Your Secret Messages
What’s This?
Every time your browser talks to a website, it sends a “letter” called a request. This letter has a header — like writing your name and address on an envelope.
Sometimes you need to add extra notes to this envelope!
Real Life Example:
- You’re sending a birthday card
- The card is your message (request body)
- The envelope says who it’s from (headers)
- You add a sticky note: “FRAGILE - Handle with care!” (extra header)
How Playwright Does It
const context = await browser.newContext({
extraHTTPHeaders: {
'Authorization': 'Bearer my-token-123',
'X-Custom-Header': 'my-value',
'Accept-Language': 'en-US'
}
});
These headers go with EVERY request!
Common Use Cases
| Header | What It Does |
|---|---|
Authorization |
Sends your login token |
Accept-Language |
Tells server your language |
X-Request-ID |
Tracks your requests |
User-Agent |
Says what browser you are |
Example: Testing with API Token
// Every page in this context
// sends the API token automatically
const context = await browser.newContext({
extraHTTPHeaders: {
'Authorization': 'Bearer abc123xyz'
}
});
const page = await context.newPage();
await page.goto('https://api.example.com');
// Token is sent automatically! 🎉
🕵️ Ignore HTTPS Errors: The Disguise That Works Everywhere
What’s This?
Websites use HTTPS to prove they’re real (like a store showing its license). Sometimes in testing, this “license” is:
- Expired (out of date)
- Self-signed (made by yourself)
- From wrong address (wrong domain)
Normally, the browser says: “DANGER! This might be fake!” and blocks you.
Real Life Example:
- You visit a new store
- The store’s license expired yesterday
- The security guard won’t let you in
- But YOU know it’s safe because it’s YOUR store!
How Playwright Does It
const context = await browser.newContext({
ignoreHTTPSErrors: true
});
Now Playwright says: “I trust this website even with certificate problems.”
When To Use This
✅ Good times to use:
- Testing on localhost with self-signed certificates
- Testing staging servers without real certificates
- Development environments
❌ Never use in:
- Production testing
- Security testing
- Real user scenarios
graph TD A["🌐 Visit HTTPS site"] --> B{Certificate OK?} B -->|Yes| C["✅ Page loads"] B -->|No| D{ignoreHTTPSErrors?} D -->|true| E["✅ Page loads anyway"] D -->|false| F["❌ Error! Blocked!"]
Complete Example
const browser = await chromium.launch();
const context = await browser.newContext({
ignoreHTTPSErrors: true
});
const page = await context.newPage();
// This works even with bad certificates!
await page.goto('https://self-signed.badssl.com');
console.log('Page loaded despite bad cert!');
📵 Offline Mode: Practice Without Internet
What’s This?
What if you want to test how your app behaves when there’s no internet? Maybe:
- The user is in airplane mode
- The WiFi disconnects
- The network is slow or broken
Playwright can pretend there’s no internet!
Real Life Example:
- You’re practicing a speech
- You turn off your phone so no one calls
- You can focus on practicing
- Later, you turn it back on
How Playwright Does It
// Turn OFF the internet
await context.setOffline(true);
// Try to load a page... it will fail!
// This is expected - we're offline!
// Turn the internet back ON
await context.setOffline(false);
Why Test Offline?
Modern apps should handle no-internet gracefully:
- Show “You’re offline” message
- Use cached content
- Queue actions for later
- Not crash or show ugly errors
Complete Example
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
// Load page while online
await page.goto('https://example.com');
console.log('Page loaded online!');
// Go offline
await context.setOffline(true);
console.log('Now offline...');
// Try to navigate - will fail
try {
await page.goto('https://google.com');
} catch (e) {
console.log('Cannot load - we are offline!');
}
// Check if app shows offline message
const offlineMsg = await page.locator('.offline-banner');
// Go back online
await context.setOffline(false);
console.log('Back online!');
graph TD A["🌐 Start Online"] --> B["setOffline true"] B --> C["📵 No Internet!"] C --> D["Test offline behavior"] D --> E["setOffline false"] E --> F["🌐 Back Online!"]
🎯 Putting It All Together
Here’s how a super spy uses ALL these tools:
const { chromium } = require('playwright');
async function superSpyTest() {
const browser = await chromium.launch();
// Create context with ALL configurations
const context = await browser.newContext({
// 🎫 Badge for protected areas
httpCredentials: {
username: 'admin',
password: 'secret123'
},
// 📦 Secret messages on every request
extraHTTPHeaders: {
'Authorization': 'Bearer token123',
'X-Test-Mode': 'true'
},
// 🕵️ Trust even bad certificates
ignoreHTTPSErrors: true
});
const page = await context.newPage();
// Visit protected staging site
await page.goto('https://staging.example.com');
// 📵 Test offline mode
await context.setOffline(true);
// ... test offline behavior ...
await context.setOffline(false);
await browser.close();
}
📝 Quick Summary
| Feature | What It Does | When To Use |
|---|---|---|
httpCredentials |
Auto-login to protected sites | Basic auth pages |
extraHTTPHeaders |
Send custom info with requests | API tokens, tracking |
ignoreHTTPSErrors |
Allow bad certificates | Dev/staging testing |
setOffline() |
Simulate no internet | Test offline behavior |
🌟 Remember!
- HTTP Credentials = Your automatic password typer
- Extra Headers = Secret notes on every letter you send
- Ignore HTTPS Errors = “I trust this site” button
- Offline Mode = Airplane mode for your browser
You’re now a Playwright Network Spy! 🕵️♀️🎉
These tools help you test real-world scenarios where networks aren’t perfect and websites need special access. Happy testing!
