playwright-ruby-client 0.6.0 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. checksums.yaml +4 -4
  2. data/documentation/README.md +33 -0
  3. data/documentation/babel.config.js +3 -0
  4. data/documentation/docs/api/accessibility.md +7 -0
  5. data/documentation/docs/api/browser.md +188 -0
  6. data/documentation/docs/api/browser_context.md +397 -0
  7. data/documentation/docs/api/browser_type.md +158 -0
  8. data/documentation/docs/api/cdp_session.md +7 -0
  9. data/documentation/docs/api/console_message.md +41 -0
  10. data/documentation/docs/api/dialog.md +71 -0
  11. data/documentation/docs/api/element_handle.md +618 -0
  12. data/documentation/docs/api/experimental/_category_.yml +3 -0
  13. data/documentation/docs/api/experimental/android.md +26 -0
  14. data/documentation/docs/api/experimental/android_device.md +92 -0
  15. data/documentation/docs/api/experimental/android_input.md +38 -0
  16. data/documentation/docs/api/experimental/android_socket.md +7 -0
  17. data/documentation/docs/api/experimental/android_web_view.md +7 -0
  18. data/documentation/docs/api/file_chooser.md +50 -0
  19. data/documentation/docs/api/frame.md +866 -0
  20. data/documentation/docs/api/js_handle.md +113 -0
  21. data/documentation/docs/api/keyboard.md +157 -0
  22. data/documentation/docs/api/mouse.md +69 -0
  23. data/documentation/docs/api/page.md +1402 -0
  24. data/documentation/docs/api/playwright.md +63 -0
  25. data/documentation/docs/api/request.md +188 -0
  26. data/documentation/docs/api/response.md +97 -0
  27. data/documentation/docs/api/route.md +79 -0
  28. data/documentation/docs/api/selectors.md +23 -0
  29. data/documentation/docs/api/touchscreen.md +8 -0
  30. data/documentation/docs/api/tracing.md +47 -0
  31. data/documentation/docs/api/web_socket.md +7 -0
  32. data/documentation/docs/api/worker.md +24 -0
  33. data/documentation/docs/article/api_coverage.mdx +11 -0
  34. data/documentation/docs/article/getting_started.md +152 -0
  35. data/documentation/docs/article/guides/_category_.yml +3 -0
  36. data/documentation/docs/article/guides/download_playwright_driver.md +49 -0
  37. data/documentation/docs/article/guides/launch_browser.md +119 -0
  38. data/documentation/docs/article/guides/rails_integration.md +205 -0
  39. data/documentation/docs/article/guides/recording_video.md +79 -0
  40. data/{docs → documentation/docs/include}/api_coverage.md +4 -3
  41. data/documentation/docusaurus.config.js +107 -0
  42. data/documentation/package.json +39 -0
  43. data/documentation/sidebars.js +15 -0
  44. data/documentation/src/components/HomepageFeatures.js +61 -0
  45. data/documentation/src/components/HomepageFeatures.module.css +13 -0
  46. data/documentation/src/css/custom.css +44 -0
  47. data/documentation/src/pages/index.js +50 -0
  48. data/documentation/src/pages/index.module.css +41 -0
  49. data/documentation/src/pages/markdown-page.md +7 -0
  50. data/documentation/static/.nojekyll +0 -0
  51. data/documentation/static/img/playwright-logo.svg +9 -0
  52. data/documentation/static/img/undraw_dropdown_menu.svg +1 -0
  53. data/documentation/static/img/undraw_web_development.svg +1 -0
  54. data/documentation/static/img/undraw_windows.svg +1 -0
  55. data/documentation/yarn.lock +8785 -0
  56. data/lib/playwright/channel_owners/binding_call.rb +33 -0
  57. data/lib/playwright/channel_owners/browser.rb +15 -27
  58. data/lib/playwright/channel_owners/browser_context.rb +15 -7
  59. data/lib/playwright/channel_owners/browser_type.rb +23 -8
  60. data/lib/playwright/channel_owners/element_handle.rb +2 -10
  61. data/lib/playwright/channel_owners/frame.rb +6 -28
  62. data/lib/playwright/channel_owners/js_handle.rb +2 -10
  63. data/lib/playwright/channel_owners/page.rb +18 -8
  64. data/lib/playwright/channel_owners/worker.rb +4 -0
  65. data/lib/playwright/input_files.rb +0 -8
  66. data/lib/playwright/javascript.rb +0 -10
  67. data/lib/playwright/javascript/expression.rb +2 -7
  68. data/lib/playwright/playwright_api.rb +16 -1
  69. data/lib/playwright/tracing_impl.rb +9 -9
  70. data/lib/playwright/version.rb +1 -1
  71. data/lib/playwright_api/accessibility.rb +7 -89
  72. data/lib/playwright_api/android.rb +10 -66
  73. data/lib/playwright_api/android_device.rb +10 -9
  74. data/lib/playwright_api/browser.rb +21 -172
  75. data/lib/playwright_api/browser_context.rb +54 -617
  76. data/lib/playwright_api/browser_type.rb +20 -108
  77. data/lib/playwright_api/cdp_session.rb +2 -25
  78. data/lib/playwright_api/console_message.rb +6 -6
  79. data/lib/playwright_api/dialog.rb +11 -92
  80. data/lib/playwright_api/element_handle.rb +60 -362
  81. data/lib/playwright_api/file_chooser.rb +0 -28
  82. data/lib/playwright_api/frame.rb +74 -713
  83. data/lib/playwright_api/js_handle.rb +16 -90
  84. data/lib/playwright_api/keyboard.rb +21 -213
  85. data/lib/playwright_api/mouse.rb +1 -45
  86. data/lib/playwright_api/page.rb +181 -1647
  87. data/lib/playwright_api/playwright.rb +14 -117
  88. data/lib/playwright_api/request.rb +15 -121
  89. data/lib/playwright_api/response.rb +7 -7
  90. data/lib/playwright_api/route.rb +8 -105
  91. data/lib/playwright_api/selectors.rb +6 -97
  92. data/lib/playwright_api/tracing.rb +7 -73
  93. data/lib/playwright_api/web_socket.rb +1 -1
  94. data/lib/playwright_api/worker.rb +28 -42
  95. metadata +57 -4
  96. data/lib/playwright/javascript/function.rb +0 -67
@@ -1,45 +1,14 @@
1
1
  module Playwright
2
2
  # - extends: [EventEmitter]
3
- #
3
+ #
4
4
  # BrowserContexts provide a way to operate multiple independent browser sessions.
5
- #
5
+ #
6
6
  # If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser
7
7
  # context.
8
- #
8
+ #
9
9
  # Playwright allows creation of "incognito" browser contexts with `browser.newContext()` method. "Incognito" browser
10
10
  # contexts don't write any browsing data to disk.
11
- #
12
11
  #
13
- # ```js
14
- # // Create a new incognito browser context
15
- # const context = await browser.newContext();
16
- # // Create a new page inside context.
17
- # const page = await context.newPage();
18
- # await page.goto('https://example.com');
19
- # // Dispose context once it's no longer needed.
20
- # await context.close();
21
- # ```
22
- #
23
- # ```java
24
- # // Create a new incognito browser context
25
- # BrowserContext context = browser.newContext();
26
- # // Create a new page inside context.
27
- # Page page = context.newPage();
28
- # page.navigate("https://example.com");
29
- # // Dispose context once it is no longer needed.
30
- # context.close();
31
- # ```
32
- #
33
- # ```python async
34
- # # create a new incognito browser context
35
- # context = await browser.new_context()
36
- # # create a new page inside context.
37
- # page = await context.new_page()
38
- # await page.goto("https://example.com")
39
- # # dispose context once it is no longer needed.
40
- # await context.close()
41
- # ```
42
- #
43
12
  # ```python sync
44
13
  # # create a new incognito browser context
45
14
  # context = browser.new_context()
@@ -49,18 +18,6 @@ module Playwright
49
18
  # # dispose context once it is no longer needed.
50
19
  # context.close()
51
20
  # ```
52
- #
53
- # ```csharp
54
- # using var playwright = await Playwright.CreateAsync();
55
- # var browser = await playwright.Firefox.LaunchAsync(headless: false);
56
- # // Create a new incognito browser context
57
- # var context = await browser.NewContextAsync();
58
- # // Create a new page inside context.
59
- # var page = await context.NewPageAsync();
60
- # await page.GotoAsync("https://bing.com");
61
- # // Dispose context once it is no longer needed.
62
- # await context.CloseAsync();
63
- # ```
64
21
  class BrowserContext < PlaywrightApi
65
22
 
66
23
  def tracing # property
@@ -69,27 +26,10 @@ module Playwright
69
26
 
70
27
  # Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be
71
28
  # obtained via [`method: BrowserContext.cookies`].
72
- #
73
29
  #
74
- # ```js
75
- # await browserContext.addCookies([cookieObject1, cookieObject2]);
76
- # ```
77
- #
78
- # ```java
79
- # browserContext.addCookies(Arrays.asList(cookieObject1, cookieObject2));
80
- # ```
81
- #
82
- # ```python async
83
- # await browser_context.add_cookies([cookie_object1, cookie_object2])
84
- # ```
85
- #
86
30
  # ```python sync
87
31
  # browser_context.add_cookies([cookie_object1, cookie_object2])
88
32
  # ```
89
- #
90
- # ```csharp
91
- # await context.AddCookiesAsync(new[] { cookie1, cookie2 });
92
- # ```
93
33
  def add_cookies(cookies)
94
34
  wrap_impl(@impl.add_cookies(unwrap_impl(cookies)))
95
35
  end
@@ -98,45 +38,17 @@ module Playwright
98
38
  # - Whenever a page is created in the browser context or is navigated.
99
39
  # - Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is
100
40
  # evaluated in the context of the newly attached frame.
101
- #
41
+ #
102
42
  # The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend
103
43
  # the JavaScript environment, e.g. to seed `Math.random`.
104
- #
105
- # An example of overriding `Math.random` before the page loads:
106
- #
107
44
  #
108
- # ```js browser
109
- # // preload.js
110
- # Math.random = () => 42;
111
- # ```
112
- #
45
+ # An example of overriding `Math.random` before the page loads:
113
46
  #
114
- # ```js
115
- # // In your playwright script, assuming the preload.js file is in same directory.
116
- # await browserContext.addInitScript({
117
- # path: 'preload.js'
118
- # });
119
- # ```
120
- #
121
- # ```java
122
- # // In your playwright script, assuming the preload.js file is in same directory.
123
- # browserContext.addInitScript(Paths.get("preload.js"));
124
- # ```
125
- #
126
- # ```python async
127
- # # in your playwright script, assuming the preload.js file is in same directory.
128
- # await browser_context.add_init_script(path="preload.js")
129
- # ```
130
- #
131
47
  # ```python sync
132
48
  # # in your playwright script, assuming the preload.js file is in same directory.
133
49
  # browser_context.add_init_script(path="preload.js")
134
50
  # ```
135
- #
136
- # ```csharp
137
- # await context.AddInitScriptAsync(scriptPath: "preload.js");
138
- # ```
139
- #
51
+ #
140
52
  # > NOTE: The order of evaluation of multiple scripts installed via [`method: BrowserContext.addInitScript`] and
141
53
  # [`method: Page.addInitScript`] is not defined.
142
54
  def add_init_script(path: nil, script: nil)
@@ -144,7 +56,7 @@ module Playwright
144
56
  end
145
57
 
146
58
  # > NOTE: Background pages are only supported on Chromium-based browsers.
147
- #
59
+ #
148
60
  # All existing background pages in the context.
149
61
  def background_pages
150
62
  raise NotImplementedError.new('background_pages is not implemented yet.')
@@ -161,50 +73,19 @@ module Playwright
161
73
  end
162
74
 
163
75
  # Clears all permission overrides for the browser context.
164
- #
165
76
  #
166
- # ```js
167
- # const context = await browser.newContext();
168
- # await context.grantPermissions(['clipboard-read']);
169
- # // do stuff ..
170
- # context.clearPermissions();
171
- # ```
172
- #
173
- # ```java
174
- # BrowserContext context = browser.newContext();
175
- # context.grantPermissions(Arrays.asList("clipboard-read"));
176
- # // do stuff ..
177
- # context.clearPermissions();
178
- # ```
179
- #
180
- # ```python async
181
- # context = await browser.new_context()
182
- # await context.grant_permissions(["clipboard-read"])
183
- # # do stuff ..
184
- # context.clear_permissions()
185
- # ```
186
- #
187
77
  # ```python sync
188
78
  # context = browser.new_context()
189
79
  # context.grant_permissions(["clipboard-read"])
190
80
  # # do stuff ..
191
81
  # context.clear_permissions()
192
82
  # ```
193
- #
194
- # ```csharp
195
- # var context = await browser.NewContextAsync();
196
- # await context.GrantPermissionsAsync(new[] { "clipboard-read" });
197
- # // Alternatively, you can use the helper class ContextPermissions
198
- # // to specify the permissions...
199
- # // do stuff ...
200
- # await context.ClearPermissionsAsync();
201
- # ```
202
83
  def clear_permissions
203
84
  wrap_impl(@impl.clear_permissions)
204
85
  end
205
86
 
206
87
  # Closes the browser context. All the pages that belong to the browser context will be closed.
207
- #
88
+ #
208
89
  # > NOTE: The default browser context cannot be closed.
209
90
  def close
210
91
  wrap_impl(@impl.close)
@@ -219,90 +100,17 @@ module Playwright
219
100
  # The method adds a function called `name` on the `window` object of every frame in every page in the context. When
220
101
  # called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If
221
102
  # the `callback` returns a [Promise], it will be awaited.
222
- #
103
+ #
223
104
  # The first argument of the `callback` function contains information about the caller: `{ browserContext: BrowserContext,
224
105
  # page: Page, frame: Frame }`.
225
- #
106
+ #
226
107
  # See [`method: Page.exposeBinding`] for page-only version.
227
- #
108
+ #
228
109
  # An example of exposing page URL to all frames in all pages in the context:
229
- #
230
- #
231
- # ```js
232
- # const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
233
- #
234
- # (async () => {
235
- # const browser = await webkit.launch({ headless: false });
236
- # const context = await browser.newContext();
237
- # await context.exposeBinding('pageURL', ({ page }) => page.url());
238
- # const page = await context.newPage();
239
- # await page.setContent(`
240
- # <script>
241
- # async function onClick() {
242
- # document.querySelector('div').textContent = await window.pageURL();
243
- # }
244
- # </script>
245
- # <button onclick="onClick()">Click me</button>
246
- # <div></div>
247
- # `);
248
- # await page.click('button');
249
- # })();
250
- # ```
251
- #
252
- # ```java
253
- # import com.microsoft.playwright.*;
254
- #
255
- # public class Example {
256
- # public static void main(String[] args) {
257
- # try (Playwright playwright = Playwright.create()) {
258
- # BrowserType webkit = playwright.webkit()
259
- # Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
260
- # BrowserContext context = browser.newContext();
261
- # context.exposeBinding("pageURL", (source, args) -> source.page().url());
262
- # Page page = context.newPage();
263
- # page.setContent("<script>\n" +
264
- # " async function onClick() {\n" +
265
- # " document.querySelector('div').textContent = await window.pageURL();\n" +
266
- # " }\n" +
267
- # "</script>\n" +
268
- # "<button onclick=\"onClick()\">Click me</button>\n" +
269
- # "<div></div>");
270
- # page.click("button");
271
- # }
272
- # }
273
- # }
274
- # ```
275
- #
276
- # ```python async
277
- # import asyncio
278
- # from playwright.async_api import async_playwright
279
- #
280
- # async def run(playwright):
281
- # webkit = playwright.webkit
282
- # browser = await webkit.launch(headless=false)
283
- # context = await browser.new_context()
284
- # await context.expose_binding("pageURL", lambda source: source["page"].url)
285
- # page = await context.new_page()
286
- # await page.set_content("""
287
- # <script>
288
- # async function onClick() {
289
- # document.querySelector('div').textContent = await window.pageURL();
290
- # }
291
- # </script>
292
- # <button onclick="onClick()">Click me</button>
293
- # <div></div>
294
- # """)
295
- # await page.click("button")
296
- #
297
- # async def main():
298
- # async with async_playwright() as playwright:
299
- # await run(playwright)
300
- # asyncio.run(main())
301
- # ```
302
- #
110
+ #
303
111
  # ```python sync
304
112
  # from playwright.sync_api import sync_playwright
305
- #
113
+ #
306
114
  # def run(playwright):
307
115
  # webkit = playwright.webkit
308
116
  # browser = webkit.launch(headless=false)
@@ -319,85 +127,17 @@ module Playwright
319
127
  # <div></div>
320
128
  # """)
321
129
  # page.click("button")
322
- #
130
+ #
323
131
  # with sync_playwright() as playwright:
324
132
  # run(playwright)
325
133
  # ```
326
- #
327
- # ```csharp
328
- # using Microsoft.Playwright;
329
- # using System.Threading.Tasks;
330
- #
331
- # class Program
332
- # {
333
- # public static async Task Main()
334
- # {
335
- # using var playwright = await Playwright.CreateAsync();
336
- # var browser = await playwright.Webkit.LaunchAsync(headless: false);
337
- # var context = await browser.NewContextAsync();
338
- #
339
- # await context.ExposeBindingAsync("pageURL", source => source.Page.Url);
340
- # var page = await context.NewPageAsync();
341
- # await page.SetContentAsync("<script>\n" +
342
- # " async function onClick() {\n" +
343
- # " document.querySelector('div').textContent = await window.pageURL();\n" +
344
- # " }\n" +
345
- # "</script>\n" +
346
- # "<button onclick=\"onClick()\">Click me</button>\n" +
347
- # "<div></div>");
348
- # await page.ClickAsync("button");
349
- # }
350
- # }
351
- # ```
352
- #
134
+ #
353
135
  # An example of passing an element handle:
354
- #
355
136
  #
356
- # ```js
357
- # await context.exposeBinding('clicked', async (source, element) => {
358
- # console.log(await element.textContent());
359
- # }, { handle: true });
360
- # await page.setContent(`
361
- # <script>
362
- # document.addEventListener('click', event => window.clicked(event.target));
363
- # </script>
364
- # <div>Click me</div>
365
- # <div>Or click me</div>
366
- # `);
367
- # ```
368
- #
369
- # ```java
370
- # context.exposeBinding("clicked", (source, args) -> {
371
- # ElementHandle element = (ElementHandle) args[0];
372
- # System.out.println(element.textContent());
373
- # return null;
374
- # }, new BrowserContext.ExposeBindingOptions().setHandle(true));
375
- # page.setContent("" +
376
- # "<script>\n" +
377
- # " document.addEventListener('click', event => window.clicked(event.target));\n" +
378
- # "</script>\n" +
379
- # "<div>Click me</div>\n" +
380
- # "<div>Or click me</div>\n");
381
- # ```
382
- #
383
- # ```python async
384
- # async def print(source, element):
385
- # print(await element.text_content())
386
- #
387
- # await context.expose_binding("clicked", print, handle=true)
388
- # await page.set_content("""
389
- # <script>
390
- # document.addEventListener('click', event => window.clicked(event.target));
391
- # </script>
392
- # <div>Click me</div>
393
- # <div>Or click me</div>
394
- # """)
395
- # ```
396
- #
397
137
  # ```python sync
398
138
  # def print(source, element):
399
139
  # print(element.text_content())
400
- #
140
+ #
401
141
  # context.expose_binding("clicked", print, handle=true)
402
142
  # page.set_content("""
403
143
  # <script>
@@ -407,202 +147,49 @@ module Playwright
407
147
  # <div>Or click me</div>
408
148
  # """)
409
149
  # ```
410
- #
411
- # ```csharp
412
- # var result = new TaskCompletionSource<string>();
413
- # var page = await Context.NewPageAsync();
414
- # await Context.ExposeBindingAsync("clicked", async (BindingSource _, IJSHandle t) =>
415
- # {
416
- # return result.TrySetResult(await t.AsElement.TextContentAsync());
417
- # });
418
- #
419
- # await page.SetContentAsync("<script>\n" +
420
- # " document.addEventListener('click', event => window.clicked(event.target));\n" +
421
- # "</script>\n" +
422
- # "<div>Click me</div>\n" +
423
- # "<div>Or click me</div>\n");
424
- #
425
- # await page.ClickAsync("div");
426
- # // Note: it makes sense to await the result here, because otherwise, the context
427
- # // gets closed and the binding function will throw an exception.
428
- # Assert.Equal("Click me", await result.Task);
429
- # ```
430
150
  def expose_binding(name, callback, handle: nil)
431
151
  wrap_impl(@impl.expose_binding(unwrap_impl(name), unwrap_impl(callback), handle: unwrap_impl(handle)))
432
152
  end
433
153
 
434
154
  # The method adds a function called `name` on the `window` object of every frame in every page in the context. When
435
155
  # called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
436
- #
156
+ #
437
157
  # If the `callback` returns a [Promise], it will be awaited.
438
- #
158
+ #
439
159
  # See [`method: Page.exposeFunction`] for page-only version.
440
- #
441
- # An example of adding an `md5` function to all pages in the context:
442
- #
443
- #
444
- # ```js
445
- # const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
446
- # const crypto = require('crypto');
447
- #
448
- # (async () => {
449
- # const browser = await webkit.launch({ headless: false });
450
- # const context = await browser.newContext();
451
- # await context.exposeFunction('md5', text => crypto.createHash('md5').update(text).digest('hex'));
452
- # const page = await context.newPage();
453
- # await page.setContent(`
454
- # <script>
455
- # async function onClick() {
456
- # document.querySelector('div').textContent = await window.md5('PLAYWRIGHT');
457
- # }
458
- # </script>
459
- # <button onclick="onClick()">Click me</button>
460
- # <div></div>
461
- # `);
462
- # await page.click('button');
463
- # })();
464
- # ```
465
- #
466
- # ```java
467
- # import com.microsoft.playwright.*;
468
- #
469
- # import java.nio.charset.StandardCharsets;
470
- # import java.security.MessageDigest;
471
- # import java.security.NoSuchAlgorithmException;
472
- # import java.util.Base64;
473
- #
474
- # public class Example {
475
- # public static void main(String[] args) {
476
- # try (Playwright playwright = Playwright.create()) {
477
- # BrowserType webkit = playwright.webkit()
478
- # Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
479
- # context.exposeFunction("sha1", args -> {
480
- # String text = (String) args[0];
481
- # MessageDigest crypto;
482
- # try {
483
- # crypto = MessageDigest.getInstance("SHA-1");
484
- # } catch (NoSuchAlgorithmException e) {
485
- # return null;
486
- # }
487
- # byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
488
- # return Base64.getEncoder().encodeToString(token);
489
- # });
490
- # Page page = context.newPage();
491
- # page.setContent("<script>\n" +
492
- # " async function onClick() {\n" +
493
- # " document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');\n" +
494
- # " }\n" +
495
- # "</script>\n" +
496
- # "<button onclick=\"onClick()\">Click me</button>\n" +
497
- # "<div></div>\n");
498
- # page.click("button");
499
- # }
500
- # }
501
- # }
502
- # ```
503
- #
504
- # ```python async
505
- # import asyncio
506
- # import hashlib
507
- # from playwright.async_api import async_playwright
508
- #
509
- # async def sha1(text):
510
- # m = hashlib.sha1()
511
- # m.update(bytes(text, "utf8"))
512
- # return m.hexdigest()
513
- #
514
- #
515
- # async def run(playwright):
516
- # webkit = playwright.webkit
517
- # browser = await webkit.launch(headless=False)
518
- # context = await browser.new_context()
519
- # await context.expose_function("sha1", sha1)
520
- # page = await context.new_page()
521
- # await page.set_content("""
522
- # <script>
523
- # async function onClick() {
524
- # document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
525
- # }
526
- # </script>
527
- # <button onclick="onClick()">Click me</button>
528
- # <div></div>
529
- # """)
530
- # await page.click("button")
531
- #
532
- # async def main():
533
- # async with async_playwright() as playwright:
534
- # await run(playwright)
535
- # asyncio.run(main())
536
- # ```
537
- #
160
+ #
161
+ # An example of adding a `sha256` function to all pages in the context:
162
+ #
538
163
  # ```python sync
539
164
  # import hashlib
540
165
  # from playwright.sync_api import sync_playwright
541
- #
542
- # def sha1(text):
543
- # m = hashlib.sha1()
166
+ #
167
+ # def sha256(text):
168
+ # m = hashlib.sha256()
544
169
  # m.update(bytes(text, "utf8"))
545
170
  # return m.hexdigest()
546
- #
547
- #
171
+ #
172
+ #
548
173
  # def run(playwright):
549
174
  # webkit = playwright.webkit
550
175
  # browser = webkit.launch(headless=False)
551
176
  # context = browser.new_context()
552
- # context.expose_function("sha1", sha1)
177
+ # context.expose_function("sha256", sha256)
553
178
  # page = context.new_page()
554
- # page.expose_function("sha1", sha1)
555
179
  # page.set_content("""
556
180
  # <script>
557
181
  # async function onClick() {
558
- # document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
182
+ # document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
559
183
  # }
560
184
  # </script>
561
185
  # <button onclick="onClick()">Click me</button>
562
186
  # <div></div>
563
187
  # """)
564
188
  # page.click("button")
565
- #
189
+ #
566
190
  # with sync_playwright() as playwright:
567
191
  # run(playwright)
568
192
  # ```
569
- #
570
- # ```csharp
571
- # using Microsoft.Playwright;
572
- # using System;
573
- # using System.Security.Cryptography;
574
- # using System.Threading.Tasks;
575
- #
576
- # class BrowserContextExamples
577
- # {
578
- # public static async Task AddMd5FunctionToAllPagesInContext()
579
- # {
580
- # using var playwright = await Playwright.CreateAsync();
581
- # var browser = await playwright.Webkit.LaunchAsync(headless: false);
582
- # var context = await browser.NewContextAsync();
583
- #
584
- # // NOTE: md5 is inherently insecure, and we strongly discourage using
585
- # // this in production in any shape or form
586
- # await context.ExposeFunctionAsync("sha1", (string input) =>
587
- # {
588
- # return Convert.ToBase64String(
589
- # MD5.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)));
590
- # });
591
- #
592
- # var page = await context.NewPageAsync();
593
- # await page.SetContentAsync("<script>\n" +
594
- # " async function onClick() {\n" +
595
- # " document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');\n" +
596
- # " }\n" +
597
- # "</script>\n" +
598
- # "<button onclick=\"onClick()\">Click me</button>\n" +
599
- # "<div></div>");
600
- #
601
- # await page.ClickAsync("button");
602
- # Console.WriteLine(await page.TextContentAsync("div"));
603
- # }
604
- # }
605
- # ```
606
193
  def expose_function(name, callback)
607
194
  wrap_impl(@impl.expose_function(unwrap_impl(name), unwrap_impl(callback)))
608
195
  end
@@ -614,15 +201,15 @@ module Playwright
614
201
  end
615
202
 
616
203
  # > NOTE: CDP sessions are only supported on Chromium-based browsers.
617
- #
204
+ #
618
205
  # Returns the newly created session.
619
206
  def new_cdp_session(page)
620
207
  raise NotImplementedError.new('new_cdp_session is not implemented yet.')
621
208
  end
622
209
 
623
210
  # Creates a new page in the browser context.
624
- def new_page
625
- wrap_impl(@impl.new_page)
211
+ def new_page(&block)
212
+ wrap_impl(@impl.new_page(&wrap_block_call(block)))
626
213
  end
627
214
 
628
215
  # Returns all open pages in the context.
@@ -632,34 +219,9 @@ module Playwright
632
219
 
633
220
  # Routing provides the capability to modify network requests that are made by any page in the browser context. Once route
634
221
  # is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
635
- #
222
+ #
636
223
  # An example of a naive handler that aborts all image requests:
637
- #
638
- #
639
- # ```js
640
- # const context = await browser.newContext();
641
- # await context.route('**/*.{png,jpg,jpeg}', route => route.abort());
642
- # const page = await context.newPage();
643
- # await page.goto('https://example.com');
644
- # await browser.close();
645
- # ```
646
- #
647
- # ```java
648
- # BrowserContext context = browser.newContext();
649
- # context.route("**/*.{png,jpg,jpeg}", route -> route.abort());
650
- # Page page = context.newPage();
651
- # page.navigate("https://example.com");
652
- # browser.close();
653
- # ```
654
- #
655
- # ```python async
656
- # context = await browser.new_context()
657
- # page = await context.new_page()
658
- # await context.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
659
- # await page.goto("https://example.com")
660
- # await browser.close()
661
- # ```
662
- #
224
+ #
663
225
  # ```python sync
664
226
  # context = browser.new_context()
665
227
  # page = context.new_page()
@@ -667,43 +229,9 @@ module Playwright
667
229
  # page.goto("https://example.com")
668
230
  # browser.close()
669
231
  # ```
670
- #
671
- # ```csharp
672
- # var context = await browser.NewContextAsync();
673
- # var page = await context.NewPageAsync();
674
- # await context.RouteAsync("**/*.{png,jpg,jpeg}", r => r.AbortAsync());
675
- # await page.GotoAsync("https://theverge.com");
676
- # await browser.CloseAsync();
677
- # ```
678
- #
232
+ #
679
233
  # or the same snippet using a regex pattern instead:
680
- #
681
- #
682
- # ```js
683
- # const context = await browser.newContext();
684
- # await context.route(/(\.png$)|(\.jpg$)/, route => route.abort());
685
- # const page = await context.newPage();
686
- # await page.goto('https://example.com');
687
- # await browser.close();
688
- # ```
689
- #
690
- # ```java
691
- # BrowserContext context = browser.newContext();
692
- # context.route(Pattern.compile("(\\.png$)|(\\.jpg$)"), route -> route.abort());
693
- # Page page = context.newPage();
694
- # page.navigate("https://example.com");
695
- # browser.close();
696
- # ```
697
- #
698
- # ```python async
699
- # context = await browser.new_context()
700
- # page = await context.new_page()
701
- # await context.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
702
- # page = await context.new_page()
703
- # await page.goto("https://example.com")
704
- # await browser.close()
705
- # ```
706
- #
234
+ #
707
235
  # ```python sync
708
236
  # context = browser.new_context()
709
237
  # page = context.new_page()
@@ -713,46 +241,10 @@ module Playwright
713
241
  # page.goto("https://example.com")
714
242
  # browser.close()
715
243
  # ```
716
- #
717
- # ```csharp
718
- # var context = await browser.NewContextAsync();
719
- # var page = await context.NewPageAsync();
720
- # await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r => r.AbortAsync());
721
- # await page.GotoAsync("https://theverge.com");
722
- # await browser.CloseAsync();
723
- # ```
724
- #
244
+ #
725
245
  # It is possible to examine the request to decide the route action. For example, mocking all requests that contain some
726
246
  # post data, and leaving all other requests as is:
727
- #
728
247
  #
729
- # ```js
730
- # await context.route('/api/**', route => {
731
- # if (route.request().postData().includes('my-string'))
732
- # route.fulfill({ body: 'mocked-data' });
733
- # else
734
- # route.continue();
735
- # });
736
- # ```
737
- #
738
- # ```java
739
- # context.route("/api/**", route -> {
740
- # if (route.request().postData().contains("my-string"))
741
- # route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
742
- # else
743
- # route.resume();
744
- # });
745
- # ```
746
- #
747
- # ```python async
748
- # def handle_route(route):
749
- # if ("my-string" in route.request.post_data)
750
- # route.fulfill(body="mocked-data")
751
- # else
752
- # route.continue_()
753
- # await context.route("/api/**", handle_route)
754
- # ```
755
- #
756
248
  # ```python sync
757
249
  # def handle_route(route):
758
250
  # if ("my-string" in route.request.post_data)
@@ -761,29 +253,19 @@ module Playwright
761
253
  # route.continue_()
762
254
  # context.route("/api/**", handle_route)
763
255
  # ```
764
- #
765
- # ```csharp
766
- # await page.RouteAsync("/api/**", async r =>
767
- # {
768
- # if (r.Request.PostData.Contains("my-string"))
769
- # await r.FulfillAsync(body: "mocked-data");
770
- # else
771
- # await r.ContinueAsync();
772
- # });
773
- # ```
774
- #
256
+ #
775
257
  # Page routes (set up with [`method: Page.route`]) take precedence over browser context routes when request matches both
776
258
  # handlers.
777
- #
259
+ #
778
260
  # To remove a route with its handler you can use [`method: BrowserContext.unroute`].
779
- #
261
+ #
780
262
  # > NOTE: Enabling routing disables http cache.
781
263
  def route(url, handler)
782
264
  wrap_impl(@impl.route(unwrap_impl(url), unwrap_impl(handler)))
783
265
  end
784
266
 
785
267
  # > NOTE: Service workers are only supported on Chromium-based browsers.
786
- #
268
+ #
787
269
  # All existing service workers in the context.
788
270
  def service_workers
789
271
  raise NotImplementedError.new('service_workers is not implemented yet.')
@@ -796,7 +278,7 @@ module Playwright
796
278
  # - [`method: Page.reload`]
797
279
  # - [`method: Page.setContent`]
798
280
  # - [`method: Page.waitForNavigation`]
799
- #
281
+ #
800
282
  # > NOTE: [`method: Page.setDefaultNavigationTimeout`] and [`method: Page.setDefaultTimeout`] take priority over
801
283
  # [`method: BrowserContext.setDefaultNavigationTimeout`].
802
284
  def set_default_navigation_timeout(timeout)
@@ -805,7 +287,7 @@ module Playwright
805
287
  alias_method :default_navigation_timeout=, :set_default_navigation_timeout
806
288
 
807
289
  # This setting will change the default maximum time for all the methods accepting `timeout` option.
808
- #
290
+ #
809
291
  # > NOTE: [`method: Page.setDefaultNavigationTimeout`], [`method: Page.setDefaultTimeout`] and
810
292
  # [`method: BrowserContext.setDefaultNavigationTimeout`] take priority over [`method: BrowserContext.setDefaultTimeout`].
811
293
  def set_default_timeout(timeout)
@@ -816,7 +298,7 @@ module Playwright
816
298
  # The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged
817
299
  # with page-specific extra HTTP headers set with [`method: Page.setExtraHTTPHeaders`]. If page overrides a particular
818
300
  # header, page-specific header value will be used instead of the browser context header value.
819
- #
301
+ #
820
302
  # > NOTE: [`method: BrowserContext.setExtraHTTPHeaders`] does not guarantee the order of headers in the outgoing requests.
821
303
  def set_extra_http_headers(headers)
822
304
  wrap_impl(@impl.set_extra_http_headers(unwrap_impl(headers)))
@@ -824,32 +306,11 @@ module Playwright
824
306
  alias_method :extra_http_headers=, :set_extra_http_headers
825
307
 
826
308
  # Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
827
- #
828
309
  #
829
- # ```js
830
- # await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
831
- # ```
832
- #
833
- # ```java
834
- # browserContext.setGeolocation(new Geolocation(59.95, 30.31667));
835
- # ```
836
- #
837
- # ```python async
838
- # await browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667})
839
- # ```
840
- #
841
310
  # ```python sync
842
311
  # browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667})
843
312
  # ```
844
- #
845
- # ```csharp
846
- # await context.SetGeolocationAsync(new Geolocation()
847
- # {
848
- # Latitude = 59.95f,
849
- # Longitude = 30.31667f
850
- # });
851
- # ```
852
- #
313
+ #
853
314
  # > NOTE: Consider using [`method: BrowserContext.grantPermissions`] to grant permissions for the browser context pages to
854
315
  # read its geolocation.
855
316
  def set_geolocation(geolocation)
@@ -875,36 +336,12 @@ module Playwright
875
336
 
876
337
  # Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
877
338
  # value. Will throw an error if the context closes before the event is fired. Returns the event data value.
878
- #
879
339
  #
880
- # ```js
881
- # const [page, _] = await Promise.all([
882
- # context.waitForEvent('page'),
883
- # page.click('button')
884
- # ]);
885
- # ```
886
- #
887
- # ```java
888
- # Page newPage = context.waitForPage(() -> page.click("button"));
889
- # ```
890
- #
891
- # ```python async
892
- # async with context.expect_event("page") as event_info:
893
- # await page.click("button")
894
- # page = await event_info.value
895
- # ```
896
- #
897
340
  # ```python sync
898
341
  # with context.expect_event("page") as event_info:
899
342
  # page.click("button")
900
343
  # page = event_info.value
901
344
  # ```
902
- #
903
- # ```csharp
904
- # var waitForPageEvent = context.WaitForPageAsync();
905
- # await page.ClickAsync("button");
906
- # var page = await waitForPageEvent;
907
- # ```
908
345
  def expect_event(event, predicate: nil, timeout: nil, &block)
909
346
  wrap_impl(@impl.expect_event(unwrap_impl(event), predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
910
347
  end
@@ -917,10 +354,10 @@ module Playwright
917
354
  end
918
355
 
919
356
  # > NOTE: In most cases, you should use [`method: BrowserContext.waitForEvent`].
920
- #
357
+ #
921
358
  # Waits for given `event` to fire. If predicate is provided, it passes event's value into the `predicate` function and
922
- # waits for `predicate(event)` to return a truthy value. Will throw an error if the socket is closed before the `event` is
923
- # fired.
359
+ # waits for `predicate(event)` to return a truthy value. Will throw an error if the browser context is closed before the
360
+ # `event` is fired.
924
361
  def wait_for_event(event, predicate: nil, timeout: nil)
925
362
  raise NotImplementedError.new('wait_for_event is not implemented yet.')
926
363
  end
@@ -945,12 +382,6 @@ module Playwright
945
382
  wrap_impl(@impl.pause)
946
383
  end
947
384
 
948
- # -- inherited from EventEmitter --
949
- # @nodoc
950
- def off(event, callback)
951
- event_emitter_proxy.off(event, callback)
952
- end
953
-
954
385
  # -- inherited from EventEmitter --
955
386
  # @nodoc
956
387
  def once(event, callback)
@@ -963,6 +394,12 @@ module Playwright
963
394
  event_emitter_proxy.on(event, callback)
964
395
  end
965
396
 
397
+ # -- inherited from EventEmitter --
398
+ # @nodoc
399
+ def off(event, callback)
400
+ event_emitter_proxy.off(event, callback)
401
+ end
402
+
966
403
  private def event_emitter_proxy
967
404
  @event_emitter_proxy ||= EventEmitterProxy.new(self, @impl)
968
405
  end