playwright-rs 0.12.3

Rust bindings for Microsoft Playwright
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
use crate::test_server::TestServer;
use playwright_rs::protocol::{
    BrowserContextOptions, ClearCookiesOptions, Cookie, Geolocation, GrantPermissionsOptions,
    Playwright, Viewport,
};

// ============================================================================
// context.cookies()
// ============================================================================

#[tokio::test]
async fn test_context_cookies_retrieve() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Add a cookie via add_cookies
    let cookie = Cookie {
        name: "test_cookie".to_string(),
        value: "test_value".to_string(),
        domain: "example.com".to_string(),
        path: "/".to_string(),
        expires: -1.0,
        http_only: false,
        secure: false,
        same_site: Some("Lax".to_string()),
    };
    context
        .add_cookies(&[cookie])
        .await
        .expect("Failed to add cookies");

    // Retrieve cookies
    let cookies = context.cookies(None).await.expect("Failed to get cookies");

    // Verify our cookie is present
    let found = cookies.iter().find(|c| c.name == "test_cookie");
    assert!(found.is_some(), "Cookie should be found");
    let found = found.unwrap();
    assert_eq!(found.value, "test_value");
    assert_eq!(found.domain, "example.com");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_cookies_with_url_filter() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Add cookies for two different domains
    let cookie1 = Cookie {
        name: "alpha_cookie".to_string(),
        value: "alpha_value".to_string(),
        domain: "example.com".to_string(),
        path: "/".to_string(),
        expires: -1.0,
        http_only: false,
        secure: false,
        same_site: None,
    };
    let cookie2 = Cookie {
        name: "beta_cookie".to_string(),
        value: "beta_value".to_string(),
        domain: "playwright.dev".to_string(),
        path: "/".to_string(),
        expires: -1.0,
        http_only: false,
        secure: false,
        same_site: None,
    };
    context
        .add_cookies(&[cookie1, cookie2])
        .await
        .expect("Failed to add cookies");

    // Filter by URL - only example.com cookies
    let cookies = context
        .cookies(Some(&["https://example.com"]))
        .await
        .expect("Failed to get cookies");

    let has_alpha = cookies.iter().any(|c| c.name == "alpha_cookie");
    let has_beta = cookies.iter().any(|c| c.name == "beta_cookie");
    assert!(has_alpha, "Should have example.com cookie");
    assert!(
        !has_beta,
        "Should NOT have playwright.dev cookie when filtering by example.com"
    );

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_cookies_empty_initially() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // New context should have no cookies
    let cookies = context.cookies(None).await.expect("Failed to get cookies");
    assert!(cookies.is_empty(), "New context should have no cookies");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

// ============================================================================
// context.clear_cookies()
// ============================================================================

#[tokio::test]
async fn test_context_clear_cookies_all() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Add some cookies
    let cookies = vec![
        Cookie {
            name: "cookie_one".to_string(),
            value: "value_one".to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            expires: -1.0,
            http_only: false,
            secure: false,
            same_site: None,
        },
        Cookie {
            name: "cookie_two".to_string(),
            value: "value_two".to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            expires: -1.0,
            http_only: false,
            secure: false,
            same_site: None,
        },
    ];
    context
        .add_cookies(&cookies)
        .await
        .expect("Failed to add cookies");

    // Verify cookies were added
    let before = context.cookies(None).await.expect("Failed to get cookies");
    assert_eq!(before.len(), 2, "Should have 2 cookies before clear");

    // Clear all cookies
    context
        .clear_cookies(None)
        .await
        .expect("Failed to clear cookies");

    // Verify cookies are gone
    let after = context.cookies(None).await.expect("Failed to get cookies");
    assert!(
        after.is_empty(),
        "Should have no cookies after clear_cookies"
    );

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_clear_cookies_with_name_filter() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Add two cookies
    let cookies = vec![
        Cookie {
            name: "keep_me".to_string(),
            value: "keep".to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            expires: -1.0,
            http_only: false,
            secure: false,
            same_site: None,
        },
        Cookie {
            name: "delete_me".to_string(),
            value: "delete".to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            expires: -1.0,
            http_only: false,
            secure: false,
            same_site: None,
        },
    ];
    context
        .add_cookies(&cookies)
        .await
        .expect("Failed to add cookies");

    // Clear only the "delete_me" cookie by name
    let options = ClearCookiesOptions {
        name: Some("delete_me".to_string()),
        domain: None,
        path: None,
    };
    context
        .clear_cookies(Some(options))
        .await
        .expect("Failed to clear cookies by name");

    // Verify "keep_me" remains but "delete_me" is gone
    let after = context.cookies(None).await.expect("Failed to get cookies");
    let has_keep = after.iter().any(|c| c.name == "keep_me");
    let has_delete = after.iter().any(|c| c.name == "delete_me");
    assert!(has_keep, "keep_me cookie should still exist");
    assert!(!has_delete, "delete_me cookie should have been cleared");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

// ============================================================================
// context.set_extra_http_headers()
// ============================================================================

#[tokio::test]
async fn test_context_set_extra_http_headers() {
    let server = TestServer::start().await;
    let (_pw, browser, context) = crate::common::setup_context().await;
    let page = context.new_page().await.expect("Failed to create page");

    // Set a custom header on the context
    let mut headers = std::collections::HashMap::new();
    headers.insert(
        "x-custom-header".to_string(),
        "custom-value-123".to_string(),
    );
    context
        .set_extra_http_headers(headers)
        .await
        .expect("Failed to set extra HTTP headers");

    // Navigate to the echo-headers endpoint
    page.goto(&format!("{}/echo-headers", server.url()), None)
        .await
        .expect("Failed to navigate");

    // Read the echoed headers from the page
    let headers_json = page
        .evaluate_value("document.getElementById('headers').textContent")
        .await
        .expect("Failed to evaluate headers");

    assert!(
        headers_json.contains("x-custom-header"),
        "Custom header name should be present in request. Got: {}",
        headers_json
    );
    assert!(
        headers_json.contains("custom-value-123"),
        "Custom header value should be present in request. Got: {}",
        headers_json
    );

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
    server.shutdown();
}

#[tokio::test]
async fn test_context_set_extra_http_headers_multiple() {
    let server = TestServer::start().await;
    let (_pw, browser, context) = crate::common::setup_context().await;
    let page = context.new_page().await.expect("Failed to create page");

    // Set multiple custom headers
    let mut headers = std::collections::HashMap::new();
    headers.insert("x-header-one".to_string(), "value-one".to_string());
    headers.insert("x-header-two".to_string(), "value-two".to_string());
    context
        .set_extra_http_headers(headers)
        .await
        .expect("Failed to set extra HTTP headers");

    page.goto(&format!("{}/echo-headers", server.url()), None)
        .await
        .expect("Failed to navigate");

    let headers_json = page
        .evaluate_value("document.getElementById('headers').textContent")
        .await
        .expect("Failed to evaluate headers");

    assert!(
        headers_json.contains("x-header-one"),
        "First header should be present. Got: {}",
        headers_json
    );
    assert!(
        headers_json.contains("x-header-two"),
        "Second header should be present. Got: {}",
        headers_json
    );

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
    server.shutdown();
}

// ============================================================================
// context.grant_permissions() and context.clear_permissions()
// ============================================================================

#[tokio::test]
async fn test_context_grant_permissions() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Grant geolocation permission - should not error
    context
        .grant_permissions(&["geolocation"], None)
        .await
        .expect("Failed to grant geolocation permission");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_grant_permissions_with_origin() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Grant geolocation permission for a specific origin
    let options = GrantPermissionsOptions {
        origin: Some("https://example.com".to_string()),
    };
    context
        .grant_permissions(&["geolocation"], Some(options))
        .await
        .expect("Failed to grant permission with origin");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_grant_and_clear_permissions() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Grant notifications permission
    context
        .grant_permissions(&["notifications"], None)
        .await
        .expect("Failed to grant notifications");

    // Clear all permissions - should not error
    context
        .clear_permissions()
        .await
        .expect("Failed to clear permissions");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_grant_multiple_permissions() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Grant multiple permissions at once
    context
        .grant_permissions(&["geolocation", "notifications"], None)
        .await
        .expect("Failed to grant multiple permissions");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

// ============================================================================
// context.set_geolocation()
// ============================================================================

#[tokio::test]
async fn test_context_set_geolocation() {
    // Geolocation requires a secure context. localhost is treated as secure by Chromium.
    let server = TestServer::start().await;
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Must grant permission before location can be read
    context
        .grant_permissions(&["geolocation"], None)
        .await
        .expect("Failed to grant geolocation");

    let page = context.new_page().await.expect("Failed to create page");

    // Navigate to localhost so we are in a secure context (localhost is always trusted)
    page.goto(&format!("{}/", server.url()), None)
        .await
        .expect("Failed to navigate to test server");

    // Set a specific geolocation (Eiffel Tower)
    context
        .set_geolocation(Some(Geolocation {
            latitude: 48.8584,
            longitude: 2.2945,
            accuracy: Some(10.0),
        }))
        .await
        .expect("Failed to set geolocation");

    // Read position via JS
    let lat = page
        .evaluate_value(
            r#"new Promise(resolve => {
                navigator.geolocation.getCurrentPosition(
                    pos => resolve(pos.coords.latitude.toFixed(4)),
                    err => resolve('error:' + err.message)
                )
            })"#,
        )
        .await
        .expect("Failed to evaluate geolocation");

    assert_eq!(lat, "48.8584", "Latitude should match set value");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
    server.shutdown();
}

#[tokio::test]
async fn test_context_set_geolocation_clear() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Set geolocation first
    context
        .set_geolocation(Some(Geolocation {
            latitude: 40.7128,
            longitude: -74.0060,
            accuracy: None,
        }))
        .await
        .expect("Failed to set geolocation");

    // Clear geolocation by passing None
    context
        .set_geolocation(None)
        .await
        .expect("Failed to clear geolocation");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

// ============================================================================
// context.set_offline()
// ============================================================================

#[tokio::test]
async fn test_context_set_offline_blocks_navigation() {
    let (_pw, browser, context) = crate::common::setup_context().await;
    let page = context.new_page().await.expect("Failed to create page");

    // Set context offline
    context
        .set_offline(true)
        .await
        .expect("Failed to set offline");

    // Navigation to external URL should fail
    let result = page.goto("https://example.com", None).await;
    assert!(result.is_err(), "Navigation should fail when offline");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_set_offline_then_online() {
    let server = TestServer::start().await;
    let (_pw, browser, context) = crate::common::setup_context().await;
    let page = context.new_page().await.expect("Failed to create page");

    // Set offline
    context
        .set_offline(true)
        .await
        .expect("Failed to set offline");

    // Set back online
    context
        .set_offline(false)
        .await
        .expect("Failed to set back online");

    // Navigation should work now (use local test server to avoid external network)
    page.goto(&format!("{}/", server.url()), None)
        .await
        .expect("Navigation should succeed after going back online");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
    server.shutdown();
}

// ============================================================================
// page.bring_to_front()
// ============================================================================

#[tokio::test]
async fn test_page_bring_to_front() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Create two pages
    let page1 = context.new_page().await.expect("Failed to create page 1");
    let _page2 = context.new_page().await.expect("Failed to create page 2");

    // Bring page1 to front - should not error
    page1
        .bring_to_front()
        .await
        .expect("Failed to bring page to front");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

// ============================================================================
// page.viewport_size()
// ============================================================================

#[tokio::test]
async fn test_page_viewport_size_with_viewport() {
    crate::common::init_tracing();
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    // Create context with specific viewport
    let options = BrowserContextOptions::builder()
        .viewport(Viewport {
            width: 1280,
            height: 720,
        })
        .build();
    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    // viewport_size() should return the configured viewport
    let viewport = page.viewport_size();
    assert!(
        viewport.is_some(),
        "viewport_size() should return Some when viewport is set"
    );
    let vp = viewport.unwrap();
    assert_eq!(vp.width, 1280, "Width should be 1280");
    assert_eq!(vp.height, 720, "Height should be 720");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_page_viewport_size_no_viewport() {
    crate::common::init_tracing();
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    // Create context with no viewport emulation
    let options = BrowserContextOptions::builder().no_viewport(true).build();
    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    // With no viewport, viewport_size() should return None
    let viewport = page.viewport_size();
    assert!(
        viewport.is_none(),
        "viewport_size() should return None when no_viewport is set"
    );

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_page_viewport_size_after_set() {
    crate::common::init_tracing();
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder()
        .viewport(Viewport {
            width: 800,
            height: 600,
        })
        .build();
    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    // Initial size
    let initial = page.viewport_size().expect("Should have viewport");
    assert_eq!(initial.width, 800);
    assert_eq!(initial.height, 600);

    // Change viewport
    page.set_viewport_size(Viewport {
        width: 1920,
        height: 1080,
    })
    .await
    .expect("Failed to set viewport size");

    // viewport_size() should reflect the updated size
    let updated = page
        .viewport_size()
        .expect("Should have viewport after set");
    assert_eq!(updated.width, 1920, "Width should be updated to 1920");
    assert_eq!(updated.height, 1080, "Height should be updated to 1080");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}