playwright-ruby-client 0.0.3 → 0.0.8

Sign up to get free protection for your applications and to get access to all the features.
Files changed (68) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +119 -12
  3. data/docs/api_coverage.md +354 -0
  4. data/lib/playwright.rb +8 -0
  5. data/lib/playwright/channel_owner.rb +16 -2
  6. data/lib/playwright/channel_owners/android.rb +10 -1
  7. data/lib/playwright/channel_owners/android_device.rb +163 -0
  8. data/lib/playwright/channel_owners/browser.rb +22 -29
  9. data/lib/playwright/channel_owners/browser_context.rb +43 -0
  10. data/lib/playwright/channel_owners/console_message.rb +21 -0
  11. data/lib/playwright/channel_owners/element_handle.rb +314 -0
  12. data/lib/playwright/channel_owners/frame.rb +466 -7
  13. data/lib/playwright/channel_owners/js_handle.rb +55 -0
  14. data/lib/playwright/channel_owners/page.rb +353 -5
  15. data/lib/playwright/channel_owners/request.rb +90 -0
  16. data/lib/playwright/channel_owners/webkit_browser.rb +1 -1
  17. data/lib/playwright/connection.rb +15 -14
  18. data/lib/playwright/errors.rb +1 -1
  19. data/lib/playwright/event_emitter.rb +13 -0
  20. data/lib/playwright/input_files.rb +42 -0
  21. data/lib/playwright/input_type.rb +19 -0
  22. data/lib/playwright/input_types/android_input.rb +19 -0
  23. data/lib/playwright/input_types/keyboard.rb +32 -0
  24. data/lib/playwright/input_types/mouse.rb +4 -0
  25. data/lib/playwright/input_types/touchscreen.rb +4 -0
  26. data/lib/playwright/javascript.rb +13 -0
  27. data/lib/playwright/javascript/expression.rb +67 -0
  28. data/lib/playwright/javascript/function.rb +67 -0
  29. data/lib/playwright/javascript/value_parser.rb +75 -0
  30. data/lib/playwright/javascript/value_serializer.rb +54 -0
  31. data/lib/playwright/playwright_api.rb +45 -25
  32. data/lib/playwright/select_option_values.rb +32 -0
  33. data/lib/playwright/timeout_settings.rb +19 -0
  34. data/lib/playwright/url_matcher.rb +19 -0
  35. data/lib/playwright/utils.rb +37 -0
  36. data/lib/playwright/version.rb +1 -1
  37. data/lib/playwright/wait_helper.rb +73 -0
  38. data/lib/playwright_api/accessibility.rb +60 -6
  39. data/lib/playwright_api/android.rb +33 -0
  40. data/lib/playwright_api/android_device.rb +78 -0
  41. data/lib/playwright_api/android_input.rb +25 -0
  42. data/lib/playwright_api/binding_call.rb +18 -0
  43. data/lib/playwright_api/browser.rb +136 -44
  44. data/lib/playwright_api/browser_context.rb +378 -51
  45. data/lib/playwright_api/browser_type.rb +137 -55
  46. data/lib/playwright_api/cdp_session.rb +32 -7
  47. data/lib/playwright_api/chromium_browser_context.rb +31 -0
  48. data/lib/playwright_api/console_message.rb +27 -7
  49. data/lib/playwright_api/dialog.rb +47 -3
  50. data/lib/playwright_api/download.rb +29 -5
  51. data/lib/playwright_api/element_handle.rb +429 -143
  52. data/lib/playwright_api/file_chooser.rb +13 -2
  53. data/lib/playwright_api/frame.rb +633 -179
  54. data/lib/playwright_api/js_handle.rb +97 -17
  55. data/lib/playwright_api/keyboard.rb +152 -24
  56. data/lib/playwright_api/mouse.rb +28 -3
  57. data/lib/playwright_api/page.rb +1183 -317
  58. data/lib/playwright_api/playwright.rb +174 -13
  59. data/lib/playwright_api/request.rb +115 -30
  60. data/lib/playwright_api/response.rb +22 -3
  61. data/lib/playwright_api/route.rb +63 -4
  62. data/lib/playwright_api/selectors.rb +29 -7
  63. data/lib/playwright_api/touchscreen.rb +2 -1
  64. data/lib/playwright_api/video.rb +11 -1
  65. data/lib/playwright_api/web_socket.rb +5 -5
  66. data/lib/playwright_api/worker.rb +29 -5
  67. data/playwright.gemspec +3 -0
  68. metadata +68 -2
@@ -1,6 +1,12 @@
1
1
  module Playwright
2
- # Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.
2
+ # - extends: [EventEmitter]
3
+ #
4
+ # Page provides methods to interact with a single tab in a `Browser`, or an
5
+ # [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser]
6
+ # instance might have multiple [Page] instances.
7
+ #
3
8
  # This example creates a page, navigates it to a URL, and then saves a screenshot:
9
+ #
4
10
  #
5
11
  # ```js
6
12
  # const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -14,13 +20,59 @@ module Playwright
14
20
  # await browser.close();
15
21
  # })();
16
22
  # ```
17
- # The Page class emits various events (described below) which can be handled using any of Node's native `EventEmitter` methods, such as `on`, `once` or `removeListener`.
23
+ #
24
+ # ```python async
25
+ # import asyncio
26
+ # from playwright.async_api import async_playwright
27
+ #
28
+ # async def run(playwright):
29
+ # webkit = playwright.webkit
30
+ # browser = await webkit.launch()
31
+ # context = await browser.new_context()
32
+ # page = await context.new_page()
33
+ # await page.goto("https://example.com")
34
+ # await page.screenshot(path="screenshot.png")
35
+ # await browser.close()
36
+ #
37
+ # async def main():
38
+ # async with async_playwright() as playwright:
39
+ # await run(playwright)
40
+ # asyncio.run(main())
41
+ # ```
42
+ #
43
+ # ```python sync
44
+ # from playwright.sync_api import sync_playwright
45
+ #
46
+ # def run(playwright):
47
+ # webkit = playwright.webkit
48
+ # browser = webkit.launch()
49
+ # context = browser.new_context()
50
+ # page = context.new_page()
51
+ # page.goto("https://example.com")
52
+ # page.screenshot(path="screenshot.png")
53
+ # browser.close()
54
+ #
55
+ # with sync_playwright() as playwright:
56
+ # run(playwright)
57
+ # ```
58
+ #
59
+ # The Page class emits various events (described below) which can be handled using any of Node's native
60
+ # [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or
61
+ # `removeListener`.
62
+ #
18
63
  # This example logs a message for a single page `load` event:
64
+ #
19
65
  #
20
66
  # ```js
21
67
  # page.once('load', () => console.log('Page loaded!'));
22
68
  # ```
69
+ #
70
+ # ```py
71
+ # page.once("load", lambda: print("page loaded!"))
72
+ # ```
73
+ #
23
74
  # To unsubscribe from events use the `removeListener` method:
75
+ #
24
76
  #
25
77
  # ```js
26
78
  # function logRequest(interceptedRequest) {
@@ -30,98 +82,162 @@ module Playwright
30
82
  # // Sometime later...
31
83
  # page.removeListener('request', logRequest);
32
84
  # ```
85
+ #
86
+ # ```py
87
+ # def log_request(intercepted_request):
88
+ # print("a request was made:", intercepted_request.url)
89
+ # page.on("request", log_request)
90
+ # # sometime later...
91
+ # page.remove_listener("request", log_request)
92
+ # ```
33
93
  class Page < PlaywrightApi
34
94
 
35
95
  def accessibility # property
36
- wrap_channel_owner(@channel_owner.accessibility)
96
+ wrap_impl(@impl.accessibility)
37
97
  end
38
98
 
39
- # Browser-specific Coverage implementation, only available for Chromium atm. See ChromiumCoverage for more details.
99
+ # Browser-specific Coverage implementation, only available for Chromium atm. See
100
+ # `ChromiumCoverage`(#class-chromiumcoverage) for more details.
40
101
  def coverage # property
41
102
  raise NotImplementedError.new('coverage is not implemented yet.')
42
103
  end
43
104
 
44
105
  def keyboard # property
45
- wrap_channel_owner(@channel_owner.keyboard)
106
+ wrap_impl(@impl.keyboard)
46
107
  end
47
108
 
48
109
  def mouse # property
49
- wrap_channel_owner(@channel_owner.mouse)
110
+ wrap_impl(@impl.mouse)
50
111
  end
51
112
 
52
113
  def touchscreen # property
53
- wrap_channel_owner(@channel_owner.touchscreen)
114
+ wrap_impl(@impl.touchscreen)
54
115
  end
55
116
 
56
- # The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to `null`.
57
- # Shortcut for main frame's `frame.$(selector)`.
58
- def S(selector)
59
- raise NotImplementedError.new('S is not implemented yet.')
117
+ # The method finds an element matching the specified selector within the page. If no elements match the selector, the
118
+ # return value resolves to `null`.
119
+ #
120
+ # Shortcut for main frame's [`method: Frame.$`].
121
+ def query_selector(selector)
122
+ wrap_impl(@impl.query_selector(unwrap_impl(selector)))
60
123
  end
61
124
 
62
- # The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to `[]`.
63
- # Shortcut for main frame's `frame.$$(selector)`.
64
- def SS(selector)
65
- raise NotImplementedError.new('SS is not implemented yet.')
125
+ # The method finds all elements matching the specified selector within the page. If no elements match the selector, the
126
+ # return value resolves to `[]`.
127
+ #
128
+ # Shortcut for main frame's [`method: Frame.$$`].
129
+ def query_selector_all(selector)
130
+ wrap_impl(@impl.query_selector_all(unwrap_impl(selector)))
66
131
  end
67
132
 
68
- # The method finds an element matching the specified selector within the page and passes it as a first argument to `pageFunction`. If no elements match the selector, the method throws an error. Returns the value of `pageFunction`.
69
- # If `pageFunction` returns a Promise, then `page.$eval(selector, pageFunction[, arg])` would wait for the promise to resolve and return its value.
133
+ # The method finds an element matching the specified selector within the page and passes it as a first argument to
134
+ # `pageFunction`. If no elements match the selector, the method throws an error. Returns the value of `pageFunction`.
135
+ #
136
+ # If `pageFunction` returns a [Promise], then [`method: Page.$eval`] would wait for the promise to resolve and return its
137
+ # value.
138
+ #
70
139
  # Examples:
140
+ #
71
141
  #
72
142
  # ```js
73
143
  # const searchValue = await page.$eval('#search', el => el.value);
74
144
  # const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
75
145
  # const html = await page.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
76
146
  # ```
77
- # Shortcut for main frame's `frame.$eval(selector, pageFunction[, arg])`.
78
- def Seval(selector, pageFunction, arg: nil)
79
- raise NotImplementedError.new('Seval is not implemented yet.')
147
+ #
148
+ # ```python async
149
+ # search_value = await page.eval_on_selector("#search", "el => el.value")
150
+ # preload_href = await page.eval_on_selector("link[rel=preload]", "el => el.href")
151
+ # html = await page.eval_on_selector(".main-container", "(e, suffix) => e.outer_html + suffix", "hello")
152
+ # ```
153
+ #
154
+ # ```python sync
155
+ # search_value = page.eval_on_selector("#search", "el => el.value")
156
+ # preload_href = page.eval_on_selector("link[rel=preload]", "el => el.href")
157
+ # html = page.eval_on_selector(".main-container", "(e, suffix) => e.outer_html + suffix", "hello")
158
+ # ```
159
+ #
160
+ # Shortcut for main frame's [`method: Frame.$eval`].
161
+ def eval_on_selector(selector, pageFunction, arg: nil)
162
+ wrap_impl(@impl.eval_on_selector(unwrap_impl(selector), unwrap_impl(pageFunction), arg: unwrap_impl(arg)))
80
163
  end
81
164
 
82
- # The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to `pageFunction`. Returns the result of `pageFunction` invocation.
83
- # If `pageFunction` returns a Promise, then `page.$$eval(selector, pageFunction[, arg])` would wait for the promise to resolve and return its value.
165
+ # The method finds all elements matching the specified selector within the page and passes an array of matched elements as
166
+ # a first argument to `pageFunction`. Returns the result of `pageFunction` invocation.
167
+ #
168
+ # If `pageFunction` returns a [Promise], then [`method: Page.$$eval`] would wait for the promise to resolve and return its
169
+ # value.
170
+ #
84
171
  # Examples:
172
+ #
85
173
  #
86
174
  # ```js
87
- # const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);
175
+ # const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);
176
+ # ```
177
+ #
178
+ # ```python async
179
+ # div_counts = await page.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10)
180
+ # ```
181
+ #
182
+ # ```python sync
183
+ # div_counts = page.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10)
88
184
  # ```
89
- def SSeval(selector, pageFunction, arg: nil)
90
- raise NotImplementedError.new('SSeval is not implemented yet.')
185
+ def eval_on_selector_all(selector, pageFunction, arg: nil)
186
+ wrap_impl(@impl.eval_on_selector_all(unwrap_impl(selector), unwrap_impl(pageFunction), arg: unwrap_impl(arg)))
91
187
  end
92
188
 
93
189
  # Adds a script which would be evaluated in one of the following scenarios:
190
+ # - Whenever the page is navigated.
191
+ # - Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly
192
+ # attached frame.
94
193
  #
95
- # Whenever the page is navigated.
96
- # Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.
194
+ # The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend
195
+ # the JavaScript environment, e.g. to seed `Math.random`.
97
196
  #
98
- # The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed `Math.random`.
99
197
  # An example of overriding `Math.random` before the page loads:
198
+ #
100
199
  #
101
- # ```js
200
+ # ```js browser
102
201
  # // preload.js
103
202
  # Math.random = () => 42;
203
+ # ```
104
204
  #
205
+ #
206
+ # ```js
105
207
  # // In your playwright script, assuming the preload.js file is in same directory
106
- # const preloadFile = fs.readFileSync('./preload.js', 'utf8');
107
- # await page.addInitScript(preloadFile);
208
+ # await page.addInitScript({ path: './preload.js' });
209
+ # ```
210
+ #
211
+ # ```python async
212
+ # # in your playwright script, assuming the preload.js file is in same directory
213
+ # await page.add_init_script(path="./preload.js")
214
+ # ```
215
+ #
216
+ # ```python sync
217
+ # # in your playwright script, assuming the preload.js file is in same directory
218
+ # page.add_init_script(path="./preload.js")
108
219
  # ```
109
220
  #
110
- # **NOTE** The order of evaluation of multiple scripts installed via `browserContext.addInitScript(script[, arg])` and `page.addInitScript(script[, arg])` is not defined.
221
+ # > NOTE: The order of evaluation of multiple scripts installed via [`method: BrowserContext.addInitScript`] and
222
+ # [`method: Page.addInitScript`] is not defined.
111
223
  def add_init_script(script, arg: nil)
112
224
  raise NotImplementedError.new('add_init_script is not implemented yet.')
113
225
  end
114
226
 
115
- # Adds a `<script>` tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.
116
- # Shortcut for main frame's `frame.addScriptTag(params)`.
117
- def add_script_tag(params)
118
- raise NotImplementedError.new('add_script_tag is not implemented yet.')
227
+ # Adds a `<script>` tag into the page with the desired url or content. Returns the added tag when the script's onload
228
+ # fires or when the script content was injected into frame.
229
+ #
230
+ # Shortcut for main frame's [`method: Frame.addScriptTag`].
231
+ def add_script_tag(content: nil, path: nil, type: nil, url: nil)
232
+ wrap_impl(@impl.add_script_tag(content: unwrap_impl(content), path: unwrap_impl(path), type: unwrap_impl(type), url: unwrap_impl(url)))
119
233
  end
120
234
 
121
- # Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
122
- # Shortcut for main frame's `frame.addStyleTag(params)`.
123
- def add_style_tag(params)
124
- raise NotImplementedError.new('add_style_tag is not implemented yet.')
235
+ # Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the
236
+ # content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
237
+ #
238
+ # Shortcut for main frame's [`method: Frame.addStyleTag`].
239
+ def add_style_tag(content: nil, path: nil, url: nil)
240
+ wrap_impl(@impl.add_style_tag(content: unwrap_impl(content), path: unwrap_impl(path), url: unwrap_impl(url)))
125
241
  end
126
242
 
127
243
  # Brings page to front (activates tab).
@@ -130,115 +246,151 @@ module Playwright
130
246
  end
131
247
 
132
248
  # This method checks an element matching `selector` by performing the following steps:
249
+ # 1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
250
+ # 1. Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already
251
+ # checked, this method returns immediately.
252
+ # 1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the
253
+ # element is detached during the checks, the whole action is retried.
254
+ # 1. Scroll the element into view if needed.
255
+ # 1. Use [`property: Page.mouse`] to click in the center of the element.
256
+ # 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
257
+ # 1. Ensure that the element is now checked. If not, this method rejects.
133
258
  #
134
- # Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
135
- # Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already checked, this method returns immediately.
136
- # Wait for actionability checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
137
- # Scroll the element into view if needed.
138
- # Use page.mouse to click in the center of the element.
139
- # Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
140
- # Ensure that the element is now checked. If not, this method rejects.
259
+ # When all steps combined have not finished during the specified `timeout`, this method rejects with a `TimeoutError`.
260
+ # Passing zero timeout disables this.
141
261
  #
142
- # When all steps combined have not finished during the specified `timeout`, this method rejects with a TimeoutError. Passing zero timeout disables this.
143
- # Shortcut for main frame's `frame.check(selector[, options])`.
262
+ # Shortcut for main frame's [`method: Frame.check`].
144
263
  def check(selector, force: nil, noWaitAfter: nil, timeout: nil)
145
264
  raise NotImplementedError.new('check is not implemented yet.')
146
265
  end
147
266
 
148
267
  # This method clicks an element matching `selector` by performing the following steps:
268
+ # 1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
269
+ # 1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the
270
+ # element is detached during the checks, the whole action is retried.
271
+ # 1. Scroll the element into view if needed.
272
+ # 1. Use [`property: Page.mouse`] to click in the center of the element, or the specified `position`.
273
+ # 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
149
274
  #
150
- # Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
151
- # Wait for actionability checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
152
- # Scroll the element into view if needed.
153
- # Use page.mouse to click in the center of the element, or the specified `position`.
154
- # Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
275
+ # When all steps combined have not finished during the specified `timeout`, this method rejects with a `TimeoutError`.
276
+ # Passing zero timeout disables this.
155
277
  #
156
- # When all steps combined have not finished during the specified `timeout`, this method rejects with a TimeoutError. Passing zero timeout disables this.
157
- # Shortcut for main frame's `frame.click(selector[, options])`.
278
+ # Shortcut for main frame's [`method: Frame.click`].
158
279
  def click(
159
280
  selector,
160
281
  button: nil,
161
282
  clickCount: nil,
162
283
  delay: nil,
163
- position: nil,
164
- modifiers: nil,
165
284
  force: nil,
285
+ modifiers: nil,
166
286
  noWaitAfter: nil,
287
+ position: nil,
167
288
  timeout: nil)
168
- raise NotImplementedError.new('click is not implemented yet.')
289
+ wrap_impl(@impl.click(unwrap_impl(selector), button: unwrap_impl(button), clickCount: unwrap_impl(clickCount), delay: unwrap_impl(delay), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), timeout: unwrap_impl(timeout)))
169
290
  end
170
291
 
171
- # If `runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed. If `runBeforeUnload` is `true` the method will run unload handlers, but will **not** wait for the page to close.
292
+ # If `runBeforeUnload` is `false`, does not run any unload handlers and waits for the page to be closed. If
293
+ # `runBeforeUnload` is `true` the method will run unload handlers, but will **not** wait for the page to close.
294
+ #
172
295
  # By default, `page.close()` **does not** run `beforeunload` handlers.
173
296
  #
174
- # **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned
175
- # and should be handled manually via page.on('dialog') event.
297
+ # > NOTE: if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned and should be handled manually
298
+ # via [`event: Page.dialog`] event.
176
299
  def close(runBeforeUnload: nil)
177
- raise NotImplementedError.new('close is not implemented yet.')
300
+ wrap_impl(@impl.close(runBeforeUnload: unwrap_impl(runBeforeUnload)))
178
301
  end
179
302
 
180
303
  # Gets the full HTML contents of the page, including the doctype.
181
304
  def content
182
- raise NotImplementedError.new('content is not implemented yet.')
305
+ wrap_impl(@impl.content)
183
306
  end
184
307
 
185
308
  # Get the browser context that the page belongs to.
186
309
  def context
187
- raise NotImplementedError.new('context is not implemented yet.')
310
+ wrap_impl(@impl.context)
188
311
  end
189
312
 
190
313
  # This method double clicks an element matching `selector` by performing the following steps:
314
+ # 1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
315
+ # 1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the
316
+ # element is detached during the checks, the whole action is retried.
317
+ # 1. Scroll the element into view if needed.
318
+ # 1. Use [`property: Page.mouse`] to double click in the center of the element, or the specified `position`.
319
+ # 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set. Note that if the
320
+ # first click of the `dblclick()` triggers a navigation event, this method will reject.
191
321
  #
192
- # Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
193
- # Wait for actionability checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
194
- # Scroll the element into view if needed.
195
- # Use page.mouse to double click in the center of the element, or the specified `position`.
196
- # Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set. Note that if the first click of the `dblclick()` triggers a navigation event, this method will reject.
322
+ # When all steps combined have not finished during the specified `timeout`, this method rejects with a `TimeoutError`.
323
+ # Passing zero timeout disables this.
197
324
  #
198
- # When all steps combined have not finished during the specified `timeout`, this method rejects with a TimeoutError. Passing zero timeout disables this.
325
+ # > NOTE: `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
199
326
  #
200
- # **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
201
- #
202
- # Shortcut for main frame's `frame.dblclick(selector[, options])`.
327
+ # Shortcut for main frame's [`method: Frame.dblclick`].
203
328
  def dblclick(
204
329
  selector,
205
330
  button: nil,
206
331
  delay: nil,
207
- position: nil,
208
- modifiers: nil,
209
332
  force: nil,
333
+ modifiers: nil,
210
334
  noWaitAfter: nil,
335
+ position: nil,
211
336
  timeout: nil)
212
- raise NotImplementedError.new('dblclick is not implemented yet.')
337
+ wrap_impl(@impl.dblclick(unwrap_impl(selector), button: unwrap_impl(button), delay: unwrap_impl(delay), force: unwrap_impl(force), modifiers: unwrap_impl(modifiers), noWaitAfter: unwrap_impl(noWaitAfter), position: unwrap_impl(position), timeout: unwrap_impl(timeout)))
213
338
  end
214
339
 
215
- # The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling element.click().
340
+ # The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click`
341
+ # is dispatched. This is equivalend to calling
342
+ # [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
343
+ #
216
344
  #
217
345
  # ```js
218
346
  # await page.dispatchEvent('button#submit', 'click');
219
347
  # ```
220
- # Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit` properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
221
- # Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
222
348
  #
223
- # DragEvent
224
- # FocusEvent
225
- # KeyboardEvent
226
- # MouseEvent
227
- # PointerEvent
228
- # TouchEvent
229
- # Event
349
+ # ```python async
350
+ # await page.dispatch_event("button#submit", "click")
351
+ # ```
352
+ #
353
+ # ```python sync
354
+ # page.dispatch_event("button#submit", "click")
355
+ # ```
356
+ #
357
+ # Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit` properties
358
+ # and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
359
+ #
360
+ # Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
361
+ # - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
362
+ # - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
363
+ # - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
364
+ # - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
365
+ # - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
366
+ # - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
367
+ # - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
230
368
  #
231
369
  # You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
370
+ #
232
371
  #
233
372
  # ```js
234
373
  # // Note you can only create DataTransfer in Chromium and Firefox
235
374
  # const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
236
375
  # await page.dispatchEvent('#source', 'dragstart', { dataTransfer });
237
376
  # ```
377
+ #
378
+ # ```python async
379
+ # # note you can only create data_transfer in chromium and firefox
380
+ # data_transfer = await page.evaluate_handle("new DataTransfer()")
381
+ # await page.dispatch_event("#source", "dragstart", { "dataTransfer": data_transfer })
382
+ # ```
383
+ #
384
+ # ```python sync
385
+ # # note you can only create data_transfer in chromium and firefox
386
+ # data_transfer = page.evaluate_handle("new DataTransfer()")
387
+ # page.dispatch_event("#source", "dragstart", { "dataTransfer": data_transfer })
388
+ # ```
238
389
  def dispatch_event(selector, type, eventInit: nil, timeout: nil)
239
390
  raise NotImplementedError.new('dispatch_event is not implemented yet.')
240
391
  end
241
392
 
393
+ #
242
394
  #
243
395
  # ```js
244
396
  # await page.evaluate(() => matchMedia('screen').matches);
@@ -258,6 +410,45 @@ module Playwright
258
410
  # await page.evaluate(() => matchMedia('print').matches);
259
411
  # // → false
260
412
  # ```
413
+ #
414
+ # ```python async
415
+ # await page.evaluate("matchMedia('screen').matches")
416
+ # # → True
417
+ # await page.evaluate("matchMedia('print').matches")
418
+ # # → False
419
+ #
420
+ # await page.emulate_media(media="print")
421
+ # await page.evaluate("matchMedia('screen').matches")
422
+ # # → False
423
+ # await page.evaluate("matchMedia('print').matches")
424
+ # # → True
425
+ #
426
+ # await page.emulate_media()
427
+ # await page.evaluate("matchMedia('screen').matches")
428
+ # # → True
429
+ # await page.evaluate("matchMedia('print').matches")
430
+ # # → False
431
+ # ```
432
+ #
433
+ # ```python sync
434
+ # page.evaluate("matchMedia('screen').matches")
435
+ # # → True
436
+ # page.evaluate("matchMedia('print').matches")
437
+ # # → False
438
+ #
439
+ # page.emulate_media(media="print")
440
+ # page.evaluate("matchMedia('screen').matches")
441
+ # # → False
442
+ # page.evaluate("matchMedia('print').matches")
443
+ # # → True
444
+ #
445
+ # page.emulate_media()
446
+ # page.evaluate("matchMedia('screen').matches")
447
+ # # → True
448
+ # page.evaluate("matchMedia('print').matches")
449
+ # # → False
450
+ # ```
451
+ #
261
452
  #
262
453
  # ```js
263
454
  # await page.emulateMedia({ colorScheme: 'dark' });
@@ -268,14 +459,40 @@ module Playwright
268
459
  # await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches);
269
460
  # // → false
270
461
  # ```
462
+ #
463
+ # ```python async
464
+ # await page.emulate_media(color_scheme="dark")
465
+ # await page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches")
466
+ # # → True
467
+ # await page.evaluate("matchMedia('(prefers-color-scheme: light)').matches")
468
+ # # → False
469
+ # await page.evaluate("matchMedia('(prefers-color-scheme: no-preference)').matches")
470
+ # # → False
471
+ # ```
472
+ #
473
+ # ```python sync
474
+ # page.emulate_media(color_scheme="dark")
475
+ # page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches")
476
+ # # → True
477
+ # page.evaluate("matchMedia('(prefers-color-scheme: light)').matches")
478
+ # # → False
479
+ # page.evaluate("matchMedia('(prefers-color-scheme: no-preference)').matches")
480
+ # ```
271
481
  def emulate_media(params)
272
482
  raise NotImplementedError.new('emulate_media is not implemented yet.')
273
483
  end
274
484
 
275
- # Returns the value of the `pageFunction` invacation.
276
- # If the function passed to the `page.evaluate` returns a Promise, then `page.evaluate` would wait for the promise to resolve and return its value.
277
- # If the function passed to the `page.evaluate` returns a non-Serializable value, then `page.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
485
+ # Returns the value of the `pageFunction` invocation.
486
+ #
487
+ # If the function passed to the [`method: Page.evaluate`] returns a [Promise], then [`method: Page.evaluate`] would wait
488
+ # for the promise to resolve and return its value.
489
+ #
490
+ # If the function passed to the [`method: Page.evaluate`] returns a non-[Serializable] value,
491
+ # then[ method: `Page.evaluate`] resolves to `undefined`. DevTools Protocol also supports transferring some additional
492
+ # values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
493
+ #
278
494
  # Passing argument to `pageFunction`:
495
+ #
279
496
  #
280
497
  # ```js
281
498
  # const result = await page.evaluate(([x, y]) => {
@@ -283,34 +500,106 @@ module Playwright
283
500
  # }, [7, 8]);
284
501
  # console.log(result); // prints "56"
285
502
  # ```
503
+ #
504
+ # ```python async
505
+ # result = await page.evaluate("([x, y]) => Promise.resolve(x * y)", [7, 8])
506
+ # print(result) # prints "56"
507
+ # ```
508
+ #
509
+ # ```python sync
510
+ # result = page.evaluate("([x, y]) => Promise.resolve(x * y)", [7, 8])
511
+ # print(result) # prints "56"
512
+ # ```
513
+ #
286
514
  # A string can also be passed in instead of a function:
515
+ #
287
516
  #
288
517
  # ```js
289
518
  # console.log(await page.evaluate('1 + 2')); // prints "3"
290
519
  # const x = 10;
291
520
  # console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
292
521
  # ```
293
- # ElementHandle instances can be passed as an argument to the `page.evaluate`:
522
+ #
523
+ # ```python async
524
+ # print(await page.evaluate("1 + 2")) # prints "3"
525
+ # x = 10
526
+ # print(await page.evaluate(f"1 + {x}")) # prints "11"
527
+ # ```
528
+ #
529
+ # ```python sync
530
+ # print(page.evaluate("1 + 2")) # prints "3"
531
+ # x = 10
532
+ # print(page.evaluate(f"1 + {x}")) # prints "11"
533
+ # ```
534
+ #
535
+ # `ElementHandle` instances can be passed as an argument to the [`method: Page.evaluate`]:
536
+ #
294
537
  #
295
538
  # ```js
296
539
  # const bodyHandle = await page.$('body');
297
540
  # const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
298
541
  # await bodyHandle.dispose();
299
542
  # ```
300
- # Shortcut for main frame's `frame.evaluate(pageFunction[, arg])`.
543
+ #
544
+ # ```python async
545
+ # body_handle = await page.query_selector("body")
546
+ # html = await page.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"])
547
+ # await body_handle.dispose()
548
+ # ```
549
+ #
550
+ # ```python sync
551
+ # body_handle = page.query_selector("body")
552
+ # html = page.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"])
553
+ # body_handle.dispose()
554
+ # ```
555
+ #
556
+ # Shortcut for main frame's [`method: Frame.evaluate`].
301
557
  def evaluate(pageFunction, arg: nil)
302
- raise NotImplementedError.new('evaluate is not implemented yet.')
558
+ wrap_impl(@impl.evaluate(unwrap_impl(pageFunction), arg: unwrap_impl(arg)))
303
559
  end
304
560
 
305
- # Returns the value of the `pageFunction` invacation as in-page object (JSHandle).
306
- # The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page object (JSHandle).
307
- # If the function passed to the `page.evaluateHandle` returns a Promise, then `page.evaluateHandle` would wait for the promise to resolve and return its value.
561
+ # Returns the value of the `pageFunction` invocation as in-page object (JSHandle).
562
+ #
563
+ # The only difference between [`method: Page.evaluate`] and [`method: Page.evaluateHandle`] is that
564
+ # [`method: Page.evaluateHandle`] returns in-page object (JSHandle).
565
+ #
566
+ # If the function passed to the [`method: Page.evaluateHandle`] returns a [Promise], then [`method: Page.evaluateHandle`]
567
+ # would wait for the promise to resolve and return its value.
568
+ #
569
+ #
570
+ # ```js
571
+ # const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window));
572
+ # aWindowHandle; // Handle for the window object.
573
+ # ```
574
+ #
575
+ # ```python async
576
+ # # FIXME
577
+ # a_window_handle = await page.evaluate_handle("Promise.resolve(window)")
578
+ # a_window_handle # handle for the window object.
579
+ # ```
580
+ #
581
+ # ```python sync
582
+ # a_window_handle = page.evaluate_handle("Promise.resolve(window)")
583
+ # a_window_handle # handle for the window object.
584
+ # ```
585
+ #
308
586
  # A string can also be passed in instead of a function:
587
+ #
309
588
  #
310
589
  # ```js
311
590
  # const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'
312
591
  # ```
313
- # JSHandle instances can be passed as an argument to the `page.evaluateHandle`:
592
+ #
593
+ # ```python async
594
+ # a_handle = await page.evaluate_handle("document") # handle for the "document"
595
+ # ```
596
+ #
597
+ # ```python sync
598
+ # a_handle = page.evaluate_handle("document") # handle for the "document"
599
+ # ```
600
+ #
601
+ # `JSHandle` instances can be passed as an argument to the [`method: Page.evaluateHandle`]:
602
+ #
314
603
  #
315
604
  # ```js
316
605
  # const aHandle = await page.evaluateHandle(() => document.body);
@@ -318,17 +607,37 @@ module Playwright
318
607
  # console.log(await resultHandle.jsonValue());
319
608
  # await resultHandle.dispose();
320
609
  # ```
610
+ #
611
+ # ```python async
612
+ # a_handle = await page.evaluate_handle("document.body")
613
+ # result_handle = await page.evaluate_handle("body => body.innerHTML", a_handle)
614
+ # print(await result_handle.json_value())
615
+ # await result_handle.dispose()
616
+ # ```
617
+ #
618
+ # ```python sync
619
+ # a_handle = page.evaluate_handle("document.body")
620
+ # result_handle = page.evaluate_handle("body => body.innerHTML", a_handle)
621
+ # print(result_handle.json_value())
622
+ # result_handle.dispose()
623
+ # ```
321
624
  def evaluate_handle(pageFunction, arg: nil)
322
- raise NotImplementedError.new('evaluate_handle is not implemented yet.')
625
+ wrap_impl(@impl.evaluate_handle(unwrap_impl(pageFunction), arg: unwrap_impl(arg)))
323
626
  end
324
627
 
325
- # The method adds a function called `name` on the `window` object of every frame in this page. When called, the function executes `playwrightBinding` and returns a Promise which resolves to the return value of `playwrightBinding`. If the `playwrightBinding` returns a Promise, it will be awaited.
326
- # The first argument of the `playwrightBinding` function contains information about the caller: `{ browserContext: BrowserContext, page: Page, frame: Frame }`.
327
- # See `browserContext.exposeBinding(name, playwrightBinding[, options])` for the context-wide version.
628
+ # The method adds a function called `name` on the `window` object of every frame in this page. When called, the function
629
+ # executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If the `callback` returns
630
+ # a [Promise], it will be awaited.
631
+ #
632
+ # The first argument of the `callback` function contains information about the caller: `{ browserContext: BrowserContext,
633
+ # page: Page, frame: Frame }`.
328
634
  #
329
- # **NOTE** Functions installed via `page.exposeBinding` survive navigations.
635
+ # See [`method: BrowserContext.exposeBinding`] for the context-wide version.
636
+ #
637
+ # > NOTE: Functions installed via [`method: Page.exposeBinding`] survive navigations.
330
638
  #
331
639
  # An example of exposing page URL to all frames in a page:
640
+ #
332
641
  #
333
642
  # ```js
334
643
  # const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -350,7 +659,60 @@ module Playwright
350
659
  # await page.click('button');
351
660
  # })();
352
661
  # ```
662
+ #
663
+ # ```python async
664
+ # import asyncio
665
+ # from playwright.async_api import async_playwright
666
+ #
667
+ # async def run(playwright):
668
+ # webkit = playwright.webkit
669
+ # browser = await webkit.launch(headless=false)
670
+ # context = await browser.new_context()
671
+ # page = await context.new_page()
672
+ # await page.expose_binding("pageURL", lambda source: source["page"].url)
673
+ # await page.set_content("""
674
+ # <script>
675
+ # async function onClick() {
676
+ # document.querySelector('div').textContent = await window.pageURL();
677
+ # }
678
+ # </script>
679
+ # <button onclick="onClick()">Click me</button>
680
+ # <div></div>
681
+ # """)
682
+ # await page.click("button")
683
+ #
684
+ # async def main():
685
+ # async with async_playwright() as playwright:
686
+ # await run(playwright)
687
+ # asyncio.run(main())
688
+ # ```
689
+ #
690
+ # ```python sync
691
+ # from playwright.sync_api import sync_playwright
692
+ #
693
+ # def run(playwright):
694
+ # webkit = playwright.webkit
695
+ # browser = webkit.launch(headless=false)
696
+ # context = browser.new_context()
697
+ # page = context.new_page()
698
+ # page.expose_binding("pageURL", lambda source: source["page"].url)
699
+ # page.set_content("""
700
+ # <script>
701
+ # async function onClick() {
702
+ # document.querySelector('div').textContent = await window.pageURL();
703
+ # }
704
+ # </script>
705
+ # <button onclick="onClick()">Click me</button>
706
+ # <div></div>
707
+ # """)
708
+ # page.click("button")
709
+ #
710
+ # with sync_playwright() as playwright:
711
+ # run(playwright)
712
+ # ```
713
+ #
353
714
  # An example of passing an element handle:
715
+ #
354
716
  #
355
717
  # ```js
356
718
  # await page.exposeBinding('clicked', async (source, element) => {
@@ -364,17 +726,49 @@ module Playwright
364
726
  # <div>Or click me</div>
365
727
  # `);
366
728
  # ```
367
- def expose_binding(name, playwrightBinding, handle: nil)
729
+ #
730
+ # ```python async
731
+ # async def print(source, element):
732
+ # print(await element.text_content())
733
+ #
734
+ # await page.expose_binding("clicked", print, handle=true)
735
+ # await page.set_content("""
736
+ # <script>
737
+ # document.addEventListener('click', event => window.clicked(event.target));
738
+ # </script>
739
+ # <div>Click me</div>
740
+ # <div>Or click me</div>
741
+ # """)
742
+ # ```
743
+ #
744
+ # ```python sync
745
+ # def print(source, element):
746
+ # print(element.text_content())
747
+ #
748
+ # page.expose_binding("clicked", print, handle=true)
749
+ # page.set_content("""
750
+ # <script>
751
+ # document.addEventListener('click', event => window.clicked(event.target));
752
+ # </script>
753
+ # <div>Click me</div>
754
+ # <div>Or click me</div>
755
+ # """)
756
+ # ```
757
+ def expose_binding(name, callback, handle: nil)
368
758
  raise NotImplementedError.new('expose_binding is not implemented yet.')
369
759
  end
370
760
 
371
- # The method adds a function called `name` on the `window` object of every frame in the page. When called, the function executes `playwrightFunction` and returns a Promise which resolves to the return value of `playwrightFunction`.
372
- # If the `playwrightFunction` returns a Promise, it will be awaited.
373
- # See `browserContext.exposeFunction(name, playwrightFunction)` for context-wide exposed function.
761
+ # The method adds a function called `name` on the `window` object of every frame in the page. When called, the function
762
+ # executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
763
+ #
764
+ # If the `callback` returns a [Promise], it will be awaited.
374
765
  #
375
- # **NOTE** Functions installed via `page.exposeFunction` survive navigations.
766
+ # See [`method: BrowserContext.exposeFunction`] for context-wide exposed function.
767
+ #
768
+ # > NOTE: Functions installed via [`method: Page.exposeFunction`] survive navigations.
769
+ #
770
+ # An example of adding an `sha1` function to the page:
376
771
  #
377
- # An example of adding an `md5` function to the page:
378
772
  #
379
773
  # ```js
380
774
  # const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -383,11 +777,11 @@ module Playwright
383
777
  # (async () => {
384
778
  # const browser = await webkit.launch({ headless: false });
385
779
  # const page = await browser.newPage();
386
- # await page.exposeFunction('md5', text => crypto.createHash('md5').update(text).digest('hex'));
780
+ # await page.exposeFunction('sha1', text => crypto.createHash('sha1').update(text).digest('hex'));
387
781
  # await page.setContent(`
388
782
  # <script>
389
783
  # async function onClick() {
390
- # document.querySelector('div').textContent = await window.md5('PLAYWRIGHT');
784
+ # document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
391
785
  # }
392
786
  # </script>
393
787
  # <button onclick="onClick()">Click me</button>
@@ -396,67 +790,119 @@ module Playwright
396
790
  # await page.click('button');
397
791
  # })();
398
792
  # ```
399
- # An example of adding a `window.readfile` function to the page:
400
- #
401
- # ```js
402
- # const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
403
- # const fs = require('fs');
404
793
  #
405
- # (async () => {
406
- # const browser = await chromium.launch();
407
- # const page = await browser.newPage();
408
- # page.on('console', msg => console.log(msg.text()));
409
- # await page.exposeFunction('readfile', async filePath => {
410
- # return new Promise((resolve, reject) => {
411
- # fs.readFile(filePath, 'utf8', (err, text) => {
412
- # if (err)
413
- # reject(err);
414
- # else
415
- # resolve(text);
416
- # });
417
- # });
418
- # });
419
- # await page.evaluate(async () => {
420
- # // use window.readfile to read contents of a file
421
- # const content = await window.readfile('/etc/hosts');
422
- # console.log(content);
423
- # });
424
- # await browser.close();
425
- # })();
794
+ # ```python async
795
+ # import asyncio
796
+ # import hashlib
797
+ # from playwright.async_api import async_playwright
798
+ #
799
+ # async def sha1(text):
800
+ # m = hashlib.sha1()
801
+ # m.update(bytes(text, "utf8"))
802
+ # return m.hexdigest()
803
+ #
804
+ #
805
+ # async def run(playwright):
806
+ # webkit = playwright.webkit
807
+ # browser = await webkit.launch(headless=False)
808
+ # page = await browser.new_page()
809
+ # await page.expose_function("sha1", sha1)
810
+ # await page.set_content("""
811
+ # <script>
812
+ # async function onClick() {
813
+ # document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
814
+ # }
815
+ # </script>
816
+ # <button onclick="onClick()">Click me</button>
817
+ # <div></div>
818
+ # """)
819
+ # await page.click("button")
820
+ #
821
+ # async def main():
822
+ # async with async_playwright() as playwright:
823
+ # await run(playwright)
824
+ # asyncio.run(main())
825
+ # ```
826
+ #
827
+ # ```python sync
828
+ # import hashlib
829
+ # from playwright.sync_api import sync_playwright
830
+ #
831
+ # def sha1(text):
832
+ # m = hashlib.sha1()
833
+ # m.update(bytes(text, "utf8"))
834
+ # return m.hexdigest()
835
+ #
836
+ #
837
+ # def run(playwright):
838
+ # webkit = playwright.webkit
839
+ # browser = webkit.launch(headless=False)
840
+ # page = browser.new_page()
841
+ # page.expose_function("sha1", sha1)
842
+ # page.set_content("""
843
+ # <script>
844
+ # async function onClick() {
845
+ # document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
846
+ # }
847
+ # </script>
848
+ # <button onclick="onClick()">Click me</button>
849
+ # <div></div>
850
+ # """)
851
+ # page.click("button")
852
+ #
853
+ # with sync_playwright() as playwright:
854
+ # run(playwright)
426
855
  # ```
427
- def expose_function(name, playwrightFunction)
856
+ def expose_function(name, callback)
428
857
  raise NotImplementedError.new('expose_function is not implemented yet.')
429
858
  end
430
859
 
431
- # This method waits for an element matching `selector`, waits for actionability checks, focuses the element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to clear the input field.
432
- # To send fine-grained keyboard events, use `page.type(selector, text[, options])`.
433
- # Shortcut for main frame's `frame.fill(selector, value[, options])`
860
+ # This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the
861
+ # element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an `<input>`,
862
+ # `<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to
863
+ # clear the input field.
864
+ #
865
+ # To send fine-grained keyboard events, use [`method: Page.type`].
866
+ #
867
+ # Shortcut for main frame's [`method: Frame.fill`]
434
868
  def fill(selector, value, noWaitAfter: nil, timeout: nil)
435
- raise NotImplementedError.new('fill is not implemented yet.')
869
+ wrap_impl(@impl.fill(unwrap_impl(selector), unwrap_impl(value), noWaitAfter: unwrap_impl(noWaitAfter), timeout: unwrap_impl(timeout)))
436
870
  end
437
871
 
438
- # This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
439
- # Shortcut for main frame's `frame.focus(selector[, options])`.
872
+ # This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method
873
+ # waits until a matching element appears in the DOM.
874
+ #
875
+ # Shortcut for main frame's [`method: Frame.focus`].
440
876
  def focus(selector, timeout: nil)
441
- raise NotImplementedError.new('focus is not implemented yet.')
877
+ wrap_impl(@impl.focus(unwrap_impl(selector), timeout: unwrap_impl(timeout)))
442
878
  end
443
879
 
444
880
  # Returns frame matching the specified criteria. Either `name` or `url` must be specified.
881
+ #
445
882
  #
446
883
  # ```js
447
884
  # const frame = page.frame('frame-name');
448
885
  # ```
886
+ #
887
+ # ```py
888
+ # frame = page.frame(name="frame-name")
889
+ # ```
890
+ #
449
891
  #
450
892
  # ```js
451
893
  # const frame = page.frame({ url: /.*domain.*/ });
452
894
  # ```
895
+ #
896
+ # ```py
897
+ # frame = page.frame(url=r".*domain.*")
898
+ # ```
453
899
  def frame(frameSelector)
454
- raise NotImplementedError.new('frame is not implemented yet.')
900
+ wrap_impl(@impl.frame(unwrap_impl(frameSelector)))
455
901
  end
456
902
 
457
903
  # An array of all frames attached to the page.
458
904
  def frames
459
- raise NotImplementedError.new('frames is not implemented yet.')
905
+ wrap_impl(@impl.frames)
460
906
  end
461
907
 
462
908
  # Returns element attribute value.
@@ -464,52 +910,63 @@ module Playwright
464
910
  raise NotImplementedError.new('get_attribute is not implemented yet.')
465
911
  end
466
912
 
467
- # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returns `null`.
913
+ # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the
914
+ # last redirect. If can not go back, returns `null`.
915
+ #
468
916
  # Navigate to the previous page in history.
469
917
  def go_back(timeout: nil, waitUntil: nil)
470
918
  raise NotImplementedError.new('go_back is not implemented yet.')
471
919
  end
472
920
 
473
- # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returns `null`.
921
+ # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the
922
+ # last redirect. If can not go forward, returns `null`.
923
+ #
474
924
  # Navigate to the next page in history.
475
925
  def go_forward(timeout: nil, waitUntil: nil)
476
926
  raise NotImplementedError.new('go_forward is not implemented yet.')
477
927
  end
478
928
 
479
- # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
480
- # `page.goto` will throw an error if:
929
+ # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the
930
+ # last redirect.
481
931
  #
482
- # there's an SSL error (e.g. in case of self-signed certificates).
483
- # target URL is invalid.
484
- # the `timeout` is exceeded during navigation.
485
- # the remote server does not respond or is unreachable.
486
- # the main resource failed to load.
932
+ # `page.goto` will throw an error if:
933
+ # - there's an SSL error (e.g. in case of self-signed certificates).
934
+ # - target URL is invalid.
935
+ # - the `timeout` is exceeded during navigation.
936
+ # - the remote server does not respond or is unreachable.
937
+ # - the main resource failed to load.
487
938
  #
488
- # `page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling `response.status()`.
939
+ # `page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not
940
+ # Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling
941
+ # [`method: Response.status`].
489
942
  #
490
- # **NOTE** `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
491
- # **NOTE** Headless mode doesn't support navigation to a PDF document. See the upstream issue.
943
+ # > NOTE: `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to
944
+ # `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
945
+ # > NOTE: Headless mode doesn't support navigation to a PDF document. See the
946
+ # [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
492
947
  #
493
- # Shortcut for main frame's `frame.goto(url[, options])`
494
- def goto(url, timeout: nil, waitUntil: nil, referer: nil)
495
- wrap_channel_owner(@channel_owner.goto(url, timeout: timeout, waitUntil: waitUntil, referer: referer))
948
+ # Shortcut for main frame's [`method: Frame.goto`]
949
+ def goto(url, referer: nil, timeout: nil, waitUntil: nil)
950
+ wrap_impl(@impl.goto(unwrap_impl(url), referer: unwrap_impl(referer), timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
496
951
  end
497
952
 
498
953
  # This method hovers over an element matching `selector` by performing the following steps:
954
+ # 1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
955
+ # 1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the
956
+ # element is detached during the checks, the whole action is retried.
957
+ # 1. Scroll the element into view if needed.
958
+ # 1. Use [`property: Page.mouse`] to hover over the center of the element, or the specified `position`.
959
+ # 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
499
960
  #
500
- # Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
501
- # Wait for actionability checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
502
- # Scroll the element into view if needed.
503
- # Use page.mouse to hover over the center of the element, or the specified `position`.
504
- # Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
961
+ # When all steps combined have not finished during the specified `timeout`, this method rejects with a `TimeoutError`.
962
+ # Passing zero timeout disables this.
505
963
  #
506
- # When all steps combined have not finished during the specified `timeout`, this method rejects with a TimeoutError. Passing zero timeout disables this.
507
- # Shortcut for main frame's `frame.hover(selector[, options])`.
964
+ # Shortcut for main frame's [`method: Frame.hover`].
508
965
  def hover(
509
966
  selector,
510
- position: nil,
511
- modifiers: nil,
512
967
  force: nil,
968
+ modifiers: nil,
969
+ position: nil,
513
970
  timeout: nil)
514
971
  raise NotImplementedError.new('hover is not implemented yet.')
515
972
  end
@@ -524,28 +981,61 @@ module Playwright
524
981
  raise NotImplementedError.new('inner_text is not implemented yet.')
525
982
  end
526
983
 
984
+ # Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
985
+ def checked?(selector, timeout: nil)
986
+ raise NotImplementedError.new('checked? is not implemented yet.')
987
+ end
988
+
527
989
  # Indicates that the page has been closed.
528
990
  def closed?
529
- raise NotImplementedError.new('closed? is not implemented yet.')
991
+ wrap_impl(@impl.closed?)
992
+ end
993
+
994
+ # Returns whether the element is disabled, the opposite of [enabled](./actionability.md#enabled).
995
+ def disabled?(selector, timeout: nil)
996
+ raise NotImplementedError.new('disabled? is not implemented yet.')
997
+ end
998
+
999
+ # Returns whether the element is [editable](./actionability.md#editable).
1000
+ def editable?(selector, timeout: nil)
1001
+ raise NotImplementedError.new('editable? is not implemented yet.')
1002
+ end
1003
+
1004
+ # Returns whether the element is [enabled](./actionability.md#enabled).
1005
+ def enabled?(selector, timeout: nil)
1006
+ raise NotImplementedError.new('enabled? is not implemented yet.')
1007
+ end
1008
+
1009
+ # Returns whether the element is hidden, the opposite of [visible](./actionability.md#visible).
1010
+ def hidden?(selector, timeout: nil)
1011
+ raise NotImplementedError.new('hidden? is not implemented yet.')
1012
+ end
1013
+
1014
+ # Returns whether the element is [visible](./actionability.md#visible).
1015
+ def visible?(selector, timeout: nil)
1016
+ raise NotImplementedError.new('visible? is not implemented yet.')
530
1017
  end
531
1018
 
532
1019
  # The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
533
1020
  def main_frame
534
- wrap_channel_owner(@channel_owner.main_frame)
1021
+ wrap_impl(@impl.main_frame)
535
1022
  end
536
1023
 
537
1024
  # Returns the opener for popup pages and `null` for others. If the opener has been closed already the returns `null`.
538
1025
  def opener
539
- raise NotImplementedError.new('opener is not implemented yet.')
1026
+ wrap_impl(@impl.opener)
540
1027
  end
541
1028
 
542
1029
  # Returns the PDF buffer.
543
1030
  #
544
- # **NOTE** Generating a pdf is currently only supported in Chromium headless.
1031
+ # > NOTE: Generating a pdf is currently only supported in Chromium headless.
545
1032
  #
546
- # `page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call `page.emulateMedia(params)` before calling `page.pdf()`:
1033
+ # `page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call
1034
+ # [`method: Page.emulateMedia`] before calling `page.pdf()`:
547
1035
  #
548
- # **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the `-webkit-print-color-adjust` property to force rendering of exact colors.
1036
+ # > NOTE: By default, `page.pdf()` generates a pdf with modified colors for printing. Use the
1037
+ # [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to
1038
+ # force rendering of exact colors.
549
1039
  #
550
1040
  #
551
1041
  # ```js
@@ -553,63 +1043,83 @@ module Playwright
553
1043
  # await page.emulateMedia({media: 'screen'});
554
1044
  # await page.pdf({path: 'page.pdf'});
555
1045
  # ```
556
- # The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as pixels.
557
- # A few examples:
558
- #
559
- # `page.pdf({width: 100})` - prints with width set to 100 pixels
560
- # `page.pdf({width: '100px'})` - prints with width set to 100 pixels
561
- # `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
562
1046
  #
563
- # All possible units are:
1047
+ # ```python async
1048
+ # # generates a pdf with "screen" media type.
1049
+ # await page.emulate_media(media="screen")
1050
+ # await page.pdf(path="page.pdf")
1051
+ # ```
564
1052
  #
565
- # `px` - pixel
566
- # `in` - inch
567
- # `cm` - centimeter
568
- # `mm` - millimeter
1053
+ # ```python sync
1054
+ # # generates a pdf with "screen" media type.
1055
+ # page.emulate_media(media="screen")
1056
+ # page.pdf(path="page.pdf")
1057
+ # ```
569
1058
  #
570
- # The `format` options are:
1059
+ # The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as pixels.
571
1060
  #
572
- # `Letter`: 8.5in x 11in
573
- # `Legal`: 8.5in x 14in
574
- # `Tabloid`: 11in x 17in
575
- # `Ledger`: 17in x 11in
576
- # `A0`: 33.1in x 46.8in
577
- # `A1`: 23.4in x 33.1in
578
- # `A2`: 16.54in x 23.4in
579
- # `A3`: 11.7in x 16.54in
580
- # `A4`: 8.27in x 11.7in
581
- # `A5`: 5.83in x 8.27in
582
- # `A6`: 4.13in x 5.83in
1061
+ # A few examples:
1062
+ # - `page.pdf({width: 100})` - prints with width set to 100 pixels
1063
+ # - `page.pdf({width: '100px'})` - prints with width set to 100 pixels
1064
+ # - `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
583
1065
  #
1066
+ # All possible units are:
1067
+ # - `px` - pixel
1068
+ # - `in` - inch
1069
+ # - `cm` - centimeter
1070
+ # - `mm` - millimeter
584
1071
  #
585
- # **NOTE** `headerTemplate` and `footerTemplate` markup have the following limitations:
1072
+ # The `format` options are:
1073
+ # - `Letter`: 8.5in x 11in
1074
+ # - `Legal`: 8.5in x 14in
1075
+ # - `Tabloid`: 11in x 17in
1076
+ # - `Ledger`: 17in x 11in
1077
+ # - `A0`: 33.1in x 46.8in
1078
+ # - `A1`: 23.4in x 33.1in
1079
+ # - `A2`: 16.54in x 23.4in
1080
+ # - `A3`: 11.7in x 16.54in
1081
+ # - `A4`: 8.27in x 11.7in
1082
+ # - `A5`: 5.83in x 8.27in
1083
+ # - `A6`: 4.13in x 5.83in
586
1084
  #
587
- # Script tags inside templates are not evaluated.
588
- # Page styles are not visible inside templates.
1085
+ # > NOTE: `headerTemplate` and `footerTemplate` markup have the following limitations: > 1. Script tags inside templates
1086
+ # are not evaluated. > 2. Page styles are not visible inside templates.
589
1087
  def pdf(
590
- path: nil,
591
- scale: nil,
592
1088
  displayHeaderFooter: nil,
593
- headerTemplate: nil,
594
1089
  footerTemplate: nil,
595
- printBackground: nil,
596
- landscape: nil,
597
- pageRanges: nil,
598
1090
  format: nil,
599
- width: nil,
1091
+ headerTemplate: nil,
600
1092
  height: nil,
1093
+ landscape: nil,
601
1094
  margin: nil,
602
- preferCSSPageSize: nil)
1095
+ pageRanges: nil,
1096
+ path: nil,
1097
+ preferCSSPageSize: nil,
1098
+ printBackground: nil,
1099
+ scale: nil,
1100
+ width: nil)
603
1101
  raise NotImplementedError.new('pdf is not implemented yet.')
604
1102
  end
605
1103
 
606
- # Focuses the element, and then uses `keyboard.down(key)` and `keyboard.up(key)`.
607
- # `key` can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the `key` values can be found here. Examples of the keys are:
608
- # `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
609
- # Following modification shortcuts are also suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
1104
+ # Focuses the element, and then uses [`method: Keyboard.down`] and [`method: Keyboard.up`].
1105
+ #
1106
+ # `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
1107
+ # value or a single character to generate the text for. A superset of the `key` values can be found
1108
+ # [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
1109
+ #
1110
+ # `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
1111
+ # `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
1112
+ #
1113
+ # Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
1114
+ #
610
1115
  # Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
611
- # If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
612
- # Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
1116
+ #
1117
+ # If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
1118
+ # texts.
1119
+ #
1120
+ # Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
1121
+ # modifier, modifier is pressed and being held while the subsequent key is being pressed.
1122
+ #
613
1123
  #
614
1124
  # ```js
615
1125
  # const page = await browser.newPage();
@@ -622,26 +1132,53 @@ module Playwright
622
1132
  # await page.screenshot({ path: 'O.png' });
623
1133
  # await browser.close();
624
1134
  # ```
1135
+ #
1136
+ # ```python async
1137
+ # page = await browser.new_page()
1138
+ # await page.goto("https://keycode.info")
1139
+ # await page.press("body", "A")
1140
+ # await page.screenshot(path="a.png")
1141
+ # await page.press("body", "ArrowLeft")
1142
+ # await page.screenshot(path="arrow_left.png")
1143
+ # await page.press("body", "Shift+O")
1144
+ # await page.screenshot(path="o.png")
1145
+ # await browser.close()
1146
+ # ```
1147
+ #
1148
+ # ```python sync
1149
+ # page = browser.new_page()
1150
+ # page.goto("https://keycode.info")
1151
+ # page.press("body", "A")
1152
+ # page.screenshot(path="a.png")
1153
+ # page.press("body", "ArrowLeft")
1154
+ # page.screenshot(path="arrow_left.png")
1155
+ # page.press("body", "Shift+O")
1156
+ # page.screenshot(path="o.png")
1157
+ # browser.close()
1158
+ # ```
625
1159
  def press(
626
1160
  selector,
627
1161
  key,
628
1162
  delay: nil,
629
1163
  noWaitAfter: nil,
630
1164
  timeout: nil)
631
- raise NotImplementedError.new('press is not implemented yet.')
1165
+ wrap_impl(@impl.press(unwrap_impl(selector), unwrap_impl(key), delay: unwrap_impl(delay), noWaitAfter: unwrap_impl(noWaitAfter), timeout: unwrap_impl(timeout)))
632
1166
  end
633
1167
 
634
- # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
1168
+ # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the
1169
+ # last redirect.
635
1170
  def reload(timeout: nil, waitUntil: nil)
636
- raise NotImplementedError.new('reload is not implemented yet.')
1171
+ wrap_impl(@impl.reload(timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
637
1172
  end
638
1173
 
639
1174
  # Routing provides the capability to modify network requests that are made by a page.
1175
+ #
640
1176
  # Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
641
1177
  #
642
- # **NOTE** The handler will only be called for the first url if the response is a redirect.
1178
+ # > NOTE: The handler will only be called for the first url if the response is a redirect.
643
1179
  #
644
1180
  # An example of a naïve handler that aborts all image requests:
1181
+ #
645
1182
  #
646
1183
  # ```js
647
1184
  # const page = await browser.newPage();
@@ -649,7 +1186,23 @@ module Playwright
649
1186
  # await page.goto('https://example.com');
650
1187
  # await browser.close();
651
1188
  # ```
1189
+ #
1190
+ # ```python async
1191
+ # page = await browser.new_page()
1192
+ # await page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
1193
+ # await page.goto("https://example.com")
1194
+ # await browser.close()
1195
+ # ```
1196
+ #
1197
+ # ```python sync
1198
+ # page = browser.new_page()
1199
+ # page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
1200
+ # page.goto("https://example.com")
1201
+ # browser.close()
1202
+ # ```
1203
+ #
652
1204
  # or the same snippet using a regex pattern instead:
1205
+ #
653
1206
  #
654
1207
  # ```js
655
1208
  # const page = await browser.newPage();
@@ -657,87 +1210,138 @@ module Playwright
657
1210
  # await page.goto('https://example.com');
658
1211
  # await browser.close();
659
1212
  # ```
660
- # Page routes take precedence over browser context routes (set up with `browserContext.route(url, handler)`) when request matches both handlers.
661
1213
  #
662
- # **NOTE** Enabling routing disables http cache.
1214
+ # ```python async
1215
+ # page = await browser.new_page()
1216
+ # await page.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
1217
+ # await page.goto("https://example.com")
1218
+ # await browser.close()
1219
+ # ```
1220
+ #
1221
+ # ```python sync
1222
+ # page = browser.new_page()
1223
+ # page.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
1224
+ # page.goto("https://example.com")
1225
+ # browser.close()
1226
+ # ```
1227
+ #
1228
+ # Page routes take precedence over browser context routes (set up with [`method: BrowserContext.route`]) when request
1229
+ # matches both handlers.
1230
+ #
1231
+ # > NOTE: Enabling routing disables http cache.
663
1232
  def route(url, handler)
664
1233
  raise NotImplementedError.new('route is not implemented yet.')
665
1234
  end
666
1235
 
667
1236
  # Returns the buffer with the captured screenshot.
668
1237
  #
669
- # **NOTE** Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See https://crbug.com/741689 for discussion.
1238
+ # > NOTE: Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See https://crbug.com/741689 for
1239
+ # discussion.
670
1240
  def screenshot(
671
- path: nil,
672
- type: nil,
673
- quality: nil,
674
- fullPage: nil,
675
1241
  clip: nil,
1242
+ fullPage: nil,
676
1243
  omitBackground: nil,
677
- timeout: nil)
678
- wrap_channel_owner(@channel_owner.screenshot(path: path, type: type, quality: quality, fullPage: fullPage, clip: clip, omitBackground: omitBackground, timeout: timeout))
1244
+ path: nil,
1245
+ quality: nil,
1246
+ timeout: nil,
1247
+ type: nil)
1248
+ wrap_impl(@impl.screenshot(clip: unwrap_impl(clip), fullPage: unwrap_impl(fullPage), omitBackground: unwrap_impl(omitBackground), path: unwrap_impl(path), quality: unwrap_impl(quality), timeout: unwrap_impl(timeout), type: unwrap_impl(type)))
679
1249
  end
680
1250
 
681
1251
  # Returns the array of option values that have been successfully selected.
682
- # Triggers a `change` and `input` event once all the provided options have been selected. If there's no `<select>` element matching `selector`, the method throws an error.
1252
+ #
1253
+ # Triggers a `change` and `input` event once all the provided options have been selected. If there's no `<select>` element
1254
+ # matching `selector`, the method throws an error.
1255
+ #
1256
+ # Will wait until all specified options are present in the `<select>` element.
1257
+ #
683
1258
  #
684
1259
  # ```js
685
1260
  # // single selection matching the value
686
1261
  # page.selectOption('select#colors', 'blue');
687
1262
  #
688
- # // single selection matching both the value and the label
1263
+ # // single selection matching the label
689
1264
  # page.selectOption('select#colors', { label: 'Blue' });
690
1265
  #
691
1266
  # // multiple selection
692
1267
  # page.selectOption('select#colors', ['red', 'green', 'blue']);
693
1268
  #
694
1269
  # ```
695
- # Shortcut for main frame's `frame.selectOption(selector, values[, options])`
1270
+ #
1271
+ # ```python async
1272
+ # # single selection matching the value
1273
+ # await page.select_option("select#colors", "blue")
1274
+ # # single selection matching the label
1275
+ # await page.select_option("select#colors", label="blue")
1276
+ # # multiple selection
1277
+ # await page.select_option("select#colors", value=["red", "green", "blue"])
1278
+ # ```
1279
+ #
1280
+ # ```python sync
1281
+ # # single selection matching the value
1282
+ # page.select_option("select#colors", "blue")
1283
+ # # single selection matching both the label
1284
+ # page.select_option("select#colors", label="blue")
1285
+ # # multiple selection
1286
+ # page.select_option("select#colors", value=["red", "green", "blue"])
1287
+ # ```
1288
+ #
1289
+ # Shortcut for main frame's [`method: Frame.selectOption`]
696
1290
  def select_option(selector, values, noWaitAfter: nil, timeout: nil)
697
1291
  raise NotImplementedError.new('select_option is not implemented yet.')
698
1292
  end
699
1293
 
700
1294
  def set_content(html, timeout: nil, waitUntil: nil)
701
- raise NotImplementedError.new('set_content is not implemented yet.')
1295
+ wrap_impl(@impl.set_content(unwrap_impl(html), timeout: unwrap_impl(timeout), waitUntil: unwrap_impl(waitUntil)))
702
1296
  end
1297
+ alias_method :content=, :set_content
703
1298
 
704
1299
  # This setting will change the default maximum navigation time for the following methods and related shortcuts:
1300
+ # - [`method: Page.goBack`]
1301
+ # - [`method: Page.goForward`]
1302
+ # - [`method: Page.goto`]
1303
+ # - [`method: Page.reload`]
1304
+ # - [`method: Page.setContent`]
1305
+ # - [`method: Page.waitForNavigation`]
705
1306
  #
706
- # `page.goBack([options])`
707
- # `page.goForward([options])`
708
- # `page.goto(url[, options])`
709
- # `page.reload([options])`
710
- # `page.setContent(html[, options])`
711
- # `page.waitForNavigation([options])`
712
- #
713
- #
714
- # **NOTE** `page.setDefaultNavigationTimeout(timeout)` takes priority over `page.setDefaultTimeout(timeout)`, `browserContext.setDefaultTimeout(timeout)` and `browserContext.setDefaultNavigationTimeout(timeout)`.
1307
+ # > NOTE: [`method: Page.setDefaultNavigationTimeout`] takes priority over [`method: Page.setDefaultTimeout`],
1308
+ # [`method: BrowserContext.setDefaultTimeout`] and [`method: BrowserContext.setDefaultNavigationTimeout`].
715
1309
  def set_default_navigation_timeout(timeout)
716
- raise NotImplementedError.new('set_default_navigation_timeout is not implemented yet.')
1310
+ wrap_impl(@impl.set_default_navigation_timeout(unwrap_impl(timeout)))
717
1311
  end
1312
+ alias_method :default_navigation_timeout=, :set_default_navigation_timeout
718
1313
 
719
1314
  # This setting will change the default maximum time for all the methods accepting `timeout` option.
720
1315
  #
721
- # **NOTE** `page.setDefaultNavigationTimeout(timeout)` takes priority over `page.setDefaultTimeout(timeout)`.
1316
+ # > NOTE: [`method: Page.setDefaultNavigationTimeout`] takes priority over [`method: Page.setDefaultTimeout`].
722
1317
  def set_default_timeout(timeout)
723
- raise NotImplementedError.new('set_default_timeout is not implemented yet.')
1318
+ wrap_impl(@impl.set_default_timeout(unwrap_impl(timeout)))
724
1319
  end
1320
+ alias_method :default_timeout=, :set_default_timeout
725
1321
 
726
1322
  # The extra HTTP headers will be sent with every request the page initiates.
727
1323
  #
728
- # **NOTE** page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
1324
+ # > NOTE: [`method: Page.setExtraHTTPHeaders`] does not guarantee the order of headers in the outgoing requests.
729
1325
  def set_extra_http_headers(headers)
730
1326
  raise NotImplementedError.new('set_extra_http_headers is not implemented yet.')
731
1327
  end
1328
+ alias_method :extra_http_headers=, :set_extra_http_headers
732
1329
 
733
- # This method expects `selector` to point to an input element.
734
- # Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they are resolved relative to the the current working directory. For empty array, clears the selected files.
1330
+ # This method expects `selector` to point to an
1331
+ # [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
1332
+ #
1333
+ # Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they
1334
+ # are resolved relative to the the current working directory. For empty array, clears the selected files.
735
1335
  def set_input_files(selector, files, noWaitAfter: nil, timeout: nil)
736
1336
  raise NotImplementedError.new('set_input_files is not implemented yet.')
737
1337
  end
738
1338
 
739
- # In the case of multiple pages in a single browser, each page can have its own viewport size. However, `browser.newContext([options])` allows to set viewport size (and more) for all pages in the context at once.
740
- # `page.setViewportSize` will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page.
1339
+ # In the case of multiple pages in a single browser, each page can have its own viewport size. However,
1340
+ # [`method: Browser.newContext`] allows to set viewport size (and more) for all pages in the context at once.
1341
+ #
1342
+ # `page.setViewportSize` will resize the page. A lot of websites don't expect phones to change size, so you should set the
1343
+ # viewport size before navigating to the page.
1344
+ #
741
1345
  #
742
1346
  # ```js
743
1347
  # const page = await browser.newPage();
@@ -747,29 +1351,43 @@ module Playwright
747
1351
  # });
748
1352
  # await page.goto('https://example.com');
749
1353
  # ```
1354
+ #
1355
+ # ```python async
1356
+ # page = await browser.new_page()
1357
+ # await page.set_viewport_size({"width": 640, "height": 480})
1358
+ # await page.goto("https://example.com")
1359
+ # ```
1360
+ #
1361
+ # ```python sync
1362
+ # page = browser.new_page()
1363
+ # page.set_viewport_size({"width": 640, "height": 480})
1364
+ # page.goto("https://example.com")
1365
+ # ```
750
1366
  def set_viewport_size(viewportSize)
751
- raise NotImplementedError.new('set_viewport_size is not implemented yet.')
1367
+ wrap_impl(@impl.set_viewport_size(unwrap_impl(viewportSize)))
752
1368
  end
1369
+ alias_method :viewport_size=, :set_viewport_size
753
1370
 
754
1371
  # This method taps an element matching `selector` by performing the following steps:
1372
+ # 1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
1373
+ # 1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the
1374
+ # element is detached during the checks, the whole action is retried.
1375
+ # 1. Scroll the element into view if needed.
1376
+ # 1. Use [`property: Page.touchscreen`] to tap the center of the element, or the specified `position`.
1377
+ # 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
755
1378
  #
756
- # Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
757
- # Wait for actionability checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
758
- # Scroll the element into view if needed.
759
- # Use page.touchscreen to tap the center of the element, or the specified `position`.
760
- # Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
761
- #
762
- # When all steps combined have not finished during the specified `timeout`, this method rejects with a TimeoutError. Passing zero timeout disables this.
1379
+ # When all steps combined have not finished during the specified `timeout`, this method rejects with a `TimeoutError`.
1380
+ # Passing zero timeout disables this.
763
1381
  #
764
- # **NOTE** `page.tap()` requires that the `hasTouch` option of the browser context be set to true.
1382
+ # > NOTE: [`method: Page.tap`] requires that the `hasTouch` option of the browser context be set to true.
765
1383
  #
766
- # Shortcut for main frame's `frame.tap(selector[, options])`.
1384
+ # Shortcut for main frame's [`method: Frame.tap`].
767
1385
  def tap_point(
768
1386
  selector,
769
- position: nil,
1387
+ force: nil,
770
1388
  modifiers: nil,
771
1389
  noWaitAfter: nil,
772
- force: nil,
1390
+ position: nil,
773
1391
  timeout: nil)
774
1392
  raise NotImplementedError.new('tap_point is not implemented yet.')
775
1393
  end
@@ -779,52 +1397,69 @@ module Playwright
779
1397
  raise NotImplementedError.new('text_content is not implemented yet.')
780
1398
  end
781
1399
 
782
- # Returns the page's title. Shortcut for main frame's `frame.title()`.
1400
+ # Returns the page's title. Shortcut for main frame's [`method: Frame.title`].
783
1401
  def title
784
- raise NotImplementedError.new('title is not implemented yet.')
1402
+ wrap_impl(@impl.title)
785
1403
  end
786
1404
 
787
- # Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to send fine-grained keyboard events. To fill values in form fields, use `page.fill(selector, value[, options])`.
788
- # To press a special key, like `Control` or `ArrowDown`, use `keyboard.press(key[, options])`.
1405
+ # Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to send
1406
+ # fine-grained keyboard events. To fill values in form fields, use [`method: Page.fill`].
1407
+ #
1408
+ # To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press`].
1409
+ #
789
1410
  #
790
1411
  # ```js
791
1412
  # await page.type('#mytextarea', 'Hello'); // Types instantly
792
1413
  # await page.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
793
1414
  # ```
794
- # Shortcut for main frame's `frame.type(selector, text[, options])`.
795
- def type_text(
1415
+ #
1416
+ # ```python async
1417
+ # await page.type("#mytextarea", "hello") # types instantly
1418
+ # await page.type("#mytextarea", "world", delay=100) # types slower, like a user
1419
+ # ```
1420
+ #
1421
+ # ```python sync
1422
+ # page.type("#mytextarea", "hello") # types instantly
1423
+ # page.type("#mytextarea", "world", delay=100) # types slower, like a user
1424
+ # ```
1425
+ #
1426
+ # Shortcut for main frame's [`method: Frame.type`].
1427
+ def type(
796
1428
  selector,
797
1429
  text,
798
1430
  delay: nil,
799
1431
  noWaitAfter: nil,
800
1432
  timeout: nil)
801
- raise NotImplementedError.new('type_text is not implemented yet.')
1433
+ wrap_impl(@impl.type(unwrap_impl(selector), unwrap_impl(text), delay: unwrap_impl(delay), noWaitAfter: unwrap_impl(noWaitAfter), timeout: unwrap_impl(timeout)))
802
1434
  end
803
1435
 
804
1436
  # This method unchecks an element matching `selector` by performing the following steps:
1437
+ # 1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
1438
+ # 1. Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already
1439
+ # unchecked, this method returns immediately.
1440
+ # 1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the
1441
+ # element is detached during the checks, the whole action is retried.
1442
+ # 1. Scroll the element into view if needed.
1443
+ # 1. Use [`property: Page.mouse`] to click in the center of the element.
1444
+ # 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1445
+ # 1. Ensure that the element is now unchecked. If not, this method rejects.
805
1446
  #
806
- # Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
807
- # Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already unchecked, this method returns immediately.
808
- # Wait for actionability checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
809
- # Scroll the element into view if needed.
810
- # Use page.mouse to click in the center of the element.
811
- # Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
812
- # Ensure that the element is now unchecked. If not, this method rejects.
1447
+ # When all steps combined have not finished during the specified `timeout`, this method rejects with a `TimeoutError`.
1448
+ # Passing zero timeout disables this.
813
1449
  #
814
- # When all steps combined have not finished during the specified `timeout`, this method rejects with a TimeoutError. Passing zero timeout disables this.
815
- # Shortcut for main frame's `frame.uncheck(selector[, options])`.
1450
+ # Shortcut for main frame's [`method: Frame.uncheck`].
816
1451
  def uncheck(selector, force: nil, noWaitAfter: nil, timeout: nil)
817
1452
  raise NotImplementedError.new('uncheck is not implemented yet.')
818
1453
  end
819
1454
 
820
- # Removes a route created with `page.route(url, handler)`. When `handler` is not specified, removes all routes for the `url`.
1455
+ # Removes a route created with [`method: Page.route`]. When `handler` is not specified, removes all routes for the `url`.
821
1456
  def unroute(url, handler: nil)
822
1457
  raise NotImplementedError.new('unroute is not implemented yet.')
823
1458
  end
824
1459
 
825
- # Shortcut for main frame's `frame.url()`.
1460
+ # Shortcut for main frame's [`method: Frame.url`].
826
1461
  def url
827
- raise NotImplementedError.new('url is not implemented yet.')
1462
+ wrap_impl(@impl.url)
828
1463
  end
829
1464
 
830
1465
  # Video object associated with this page.
@@ -833,17 +1468,39 @@ module Playwright
833
1468
  end
834
1469
 
835
1470
  def viewport_size
836
- raise NotImplementedError.new('viewport_size is not implemented yet.')
1471
+ wrap_impl(@impl.viewport_size)
837
1472
  end
838
1473
 
839
- # Returns the event data value.
840
- # Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the page is closed before the event is fired.
841
- def wait_for_event(event, optionsOrPredicate: nil)
842
- raise NotImplementedError.new('wait_for_event is not implemented yet.')
1474
+ # Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
1475
+ # value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
1476
+ #
1477
+ #
1478
+ # ```js
1479
+ # const [frame, _] = await Promise.all([
1480
+ # page.waitForEvent('framenavigated'),
1481
+ # page.click('button')
1482
+ # ]);
1483
+ # ```
1484
+ #
1485
+ # ```python async
1486
+ # async with page.expect_event("framenavigated") as event_info:
1487
+ # await page.click("button")
1488
+ # frame = await event_info.value
1489
+ # ```
1490
+ #
1491
+ # ```python sync
1492
+ # with page.expect_event("framenavigated") as event_info:
1493
+ # page.click("button")
1494
+ # frame = event_info.value
1495
+ # ```
1496
+ def expect_event(event, optionsOrPredicate: nil, &block)
1497
+ wrap_impl(@impl.expect_event(unwrap_impl(event), optionsOrPredicate: unwrap_impl(optionsOrPredicate), &wrap_block_call(block)))
843
1498
  end
844
1499
 
845
1500
  # Returns when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.
1501
+ #
846
1502
  # The `waitForFunction` can be used to observe viewport size change:
1503
+ #
847
1504
  #
848
1505
  # ```js
849
1506
  # const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -851,30 +1508,90 @@ module Playwright
851
1508
  # (async () => {
852
1509
  # const browser = await webkit.launch();
853
1510
  # const page = await browser.newPage();
854
- # const watchDog = page.waitForFunction('window.innerWidth < 100');
1511
+ # const watchDog = page.waitForFunction(() => window.innerWidth < 100);
855
1512
  # await page.setViewportSize({width: 50, height: 50});
856
1513
  # await watchDog;
857
1514
  # await browser.close();
858
1515
  # })();
859
1516
  # ```
860
- # To pass an argument to the predicate of `page.waitForFunction` function:
1517
+ #
1518
+ # ```python async
1519
+ # import asyncio
1520
+ # from playwright.async_api import async_playwright
1521
+ #
1522
+ # async def run(playwright):
1523
+ # webkit = playwright.webkit
1524
+ # browser = await webkit.launch()
1525
+ # page = await browser.new_page()
1526
+ # await page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);", force_expr=True)
1527
+ # await page.wait_for_function("() => window.x > 0")
1528
+ # await browser.close()
1529
+ #
1530
+ # async def main():
1531
+ # async with async_playwright() as playwright:
1532
+ # await run(playwright)
1533
+ # asyncio.run(main())
1534
+ # ```
1535
+ #
1536
+ # ```python sync
1537
+ # from playwright.sync_api import sync_playwright
1538
+ #
1539
+ # def run(playwright):
1540
+ # webkit = playwright.webkit
1541
+ # browser = webkit.launch()
1542
+ # page = browser.new_page()
1543
+ # page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);", force_expr=True)
1544
+ # page.wait_for_function("() => window.x > 0")
1545
+ # browser.close()
1546
+ #
1547
+ # with sync_playwright() as playwright:
1548
+ # run(playwright)
1549
+ # ```
1550
+ #
1551
+ # To pass an argument to the predicate of [`method: Page.waitForFunction`] function:
1552
+ #
861
1553
  #
862
1554
  # ```js
863
1555
  # const selector = '.foo';
864
1556
  # await page.waitForFunction(selector => !!document.querySelector(selector), selector);
865
1557
  # ```
866
- # Shortcut for main frame's `frame.waitForFunction(pageFunction[, arg, options])`.
1558
+ #
1559
+ # ```python async
1560
+ # selector = ".foo"
1561
+ # await page.wait_for_function("selector => !!document.querySelector(selector)", selector)
1562
+ # ```
1563
+ #
1564
+ # ```python sync
1565
+ # selector = ".foo"
1566
+ # page.wait_for_function("selector => !!document.querySelector(selector)", selector)
1567
+ # ```
1568
+ #
1569
+ # Shortcut for main frame's [`method: Frame.waitForFunction`].
867
1570
  def wait_for_function(pageFunction, arg: nil, polling: nil, timeout: nil)
868
- raise NotImplementedError.new('wait_for_function is not implemented yet.')
1571
+ wrap_impl(@impl.wait_for_function(unwrap_impl(pageFunction), arg: unwrap_impl(arg), polling: unwrap_impl(polling), timeout: unwrap_impl(timeout)))
869
1572
  end
870
1573
 
871
1574
  # Returns when the required load state has been reached.
872
- # This resolves when the page reaches a required load state, `load` by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
1575
+ #
1576
+ # This resolves when the page reaches a required load state, `load` by default. The navigation must have been committed
1577
+ # when this method is called. If current document has already reached the required state, resolves immediately.
1578
+ #
873
1579
  #
874
1580
  # ```js
875
1581
  # await page.click('button'); // Click triggers navigation.
876
1582
  # await page.waitForLoadState(); // The promise resolves after 'load' event.
877
1583
  # ```
1584
+ #
1585
+ # ```python async
1586
+ # await page.click("button") # click triggers navigation.
1587
+ # await page.wait_for_load_state() # the promise resolves after "load" event.
1588
+ # ```
1589
+ #
1590
+ # ```python sync
1591
+ # page.click("button") # click triggers navigation.
1592
+ # page.wait_for_load_state() # the promise resolves after "load" event.
1593
+ # ```
1594
+ #
878
1595
  #
879
1596
  # ```js
880
1597
  # const [popup] = await Promise.all([
@@ -884,13 +1601,38 @@ module Playwright
884
1601
  # await popup.waitForLoadState('domcontentloaded'); // The promise resolves after 'domcontentloaded' event.
885
1602
  # console.log(await popup.title()); // Popup is ready to use.
886
1603
  # ```
887
- # Shortcut for main frame's `frame.waitForLoadState([state, options])`.
1604
+ #
1605
+ # ```python async
1606
+ # async with page.expect_popup() as page_info:
1607
+ # await page.click("button") # click triggers a popup.
1608
+ # popup = await page_info.value
1609
+ # # Following resolves after "domcontentloaded" event.
1610
+ # await popup.wait_for_load_state("domcontentloaded")
1611
+ # print(await popup.title()) # popup is ready to use.
1612
+ # ```
1613
+ #
1614
+ # ```python sync
1615
+ # with page.expect_popup() as page_info:
1616
+ # page.click("button") # click triggers a popup.
1617
+ # popup = page_info.value
1618
+ # # Following resolves after "domcontentloaded" event.
1619
+ # popup.wait_for_load_state("domcontentloaded")
1620
+ # print(popup.title()) # popup is ready to use.
1621
+ # ```
1622
+ #
1623
+ # Shortcut for main frame's [`method: Frame.waitForLoadState`].
888
1624
  def wait_for_load_state(state: nil, timeout: nil)
889
- raise NotImplementedError.new('wait_for_load_state is not implemented yet.')
1625
+ wrap_impl(@impl.wait_for_load_state(state: unwrap_impl(state), timeout: unwrap_impl(timeout)))
890
1626
  end
891
1627
 
892
- # Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
893
- # This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from a `setTimeout`. Consider this example:
1628
+ # Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the
1629
+ # navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or
1630
+ # navigation due to History API usage, the navigation will resolve with `null`.
1631
+ #
1632
+ # This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly
1633
+ # cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from a `setTimeout`.
1634
+ # Consider this example:
1635
+ #
894
1636
  #
895
1637
  # ```js
896
1638
  # const [response] = await Promise.all([
@@ -898,41 +1640,97 @@ module Playwright
898
1640
  # page.click('a.delayed-navigation'), // Clicking the link will indirectly cause a navigation
899
1641
  # ]);
900
1642
  # ```
901
- # **NOTE** Usage of the History API to change the URL is considered a navigation.
902
- # Shortcut for main frame's `frame.waitForNavigation([options])`.
903
- def wait_for_navigation(timeout: nil, url: nil, waitUntil: nil)
904
- raise NotImplementedError.new('wait_for_navigation is not implemented yet.')
1643
+ #
1644
+ # ```python async
1645
+ # async with page.expect_navigation():
1646
+ # await page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
1647
+ # # Resolves after navigation has finished
1648
+ # ```
1649
+ #
1650
+ # ```python sync
1651
+ # with page.expect_navigation():
1652
+ # page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
1653
+ # # Resolves after navigation has finished
1654
+ # ```
1655
+ #
1656
+ # > NOTE: Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is
1657
+ # considered a navigation.
1658
+ #
1659
+ # Shortcut for main frame's [`method: Frame.waitForNavigation`].
1660
+ def expect_navigation(timeout: nil, url: nil, waitUntil: nil, &block)
1661
+ wrap_impl(@impl.expect_navigation(timeout: unwrap_impl(timeout), url: unwrap_impl(url), waitUntil: unwrap_impl(waitUntil), &wrap_block_call(block)))
905
1662
  end
906
1663
 
907
1664
  # Waits for the matching request and returns it.
1665
+ #
908
1666
  #
909
1667
  # ```js
910
1668
  # const firstRequest = await page.waitForRequest('http://example.com/resource');
911
1669
  # const finalRequest = await page.waitForRequest(request => request.url() === 'http://example.com' && request.method() === 'GET');
912
1670
  # return firstRequest.url();
913
1671
  # ```
1672
+ #
1673
+ # ```python async
1674
+ # async with page.expect_request("http://example.com/resource") as first:
1675
+ # await page.click('button')
1676
+ # first_request = await first.value
1677
+ #
1678
+ # async with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second:
1679
+ # await page.click('img')
1680
+ # second_request = await second.value
1681
+ # ```
1682
+ #
1683
+ # ```python sync
1684
+ # with page.expect_request("http://example.com/resource") as first:
1685
+ # page.click('button')
1686
+ # first_request = first.value
1687
+ #
1688
+ # with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second:
1689
+ # page.click('img')
1690
+ # second_request = second.value
1691
+ # ```
1692
+ #
914
1693
  #
915
1694
  # ```js
916
1695
  # await page.waitForRequest(request => request.url().searchParams.get('foo') === 'bar' && request.url().searchParams.get('foo2') === 'bar2');
917
1696
  # ```
918
- def wait_for_request(urlOrPredicate, timeout: nil)
919
- raise NotImplementedError.new('wait_for_request is not implemented yet.')
1697
+ def expect_request(urlOrPredicate, timeout: nil)
1698
+ wrap_impl(@impl.expect_request(unwrap_impl(urlOrPredicate), timeout: unwrap_impl(timeout)))
920
1699
  end
921
1700
 
922
1701
  # Returns the matched response.
1702
+ #
923
1703
  #
924
1704
  # ```js
925
1705
  # const firstResponse = await page.waitForResponse('https://example.com/resource');
926
1706
  # const finalResponse = await page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200);
927
1707
  # return finalResponse.ok();
928
1708
  # ```
929
- def wait_for_response(urlOrPredicate, timeout: nil)
930
- raise NotImplementedError.new('wait_for_response is not implemented yet.')
1709
+ #
1710
+ # ```python async
1711
+ # first_response = await page.wait_for_response("https://example.com/resource")
1712
+ # final_response = await page.wait_for_response(lambda response: response.url == "https://example.com" and response.status === 200)
1713
+ # return final_response.ok
1714
+ # ```
1715
+ #
1716
+ # ```python sync
1717
+ # first_response = page.wait_for_response("https://example.com/resource")
1718
+ # final_response = page.wait_for_response(lambda response: response.url == "https://example.com" and response.status === 200)
1719
+ # return final_response.ok
1720
+ # ```
1721
+ def expect_response(urlOrPredicate, timeout: nil)
1722
+ wrap_impl(@impl.expect_response(unwrap_impl(urlOrPredicate), timeout: unwrap_impl(timeout)))
931
1723
  end
932
1724
 
933
- # Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or `detached`.
934
- # Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
1725
+ # Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or
1726
+ # `detached`.
1727
+ #
1728
+ # Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If at
1729
+ # the moment of calling the method `selector` already satisfies the condition, the method will return immediately. If the
1730
+ # selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
1731
+ #
935
1732
  # This method works across navigations:
1733
+ #
936
1734
  #
937
1735
  # ```js
938
1736
  # const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
@@ -940,47 +1738,115 @@ module Playwright
940
1738
  # (async () => {
941
1739
  # const browser = await chromium.launch();
942
1740
  # const page = await browser.newPage();
943
- # let currentURL;
944
- # page
945
- # .waitForSelector('img')
946
- # .then(() => console.log('First URL with image: ' + currentURL));
947
- # for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
1741
+ # for (let currentURL of ['https://google.com', 'https://bbc.com']) {
948
1742
  # await page.goto(currentURL);
1743
+ # const element = await page.waitForSelector('img');
1744
+ # console.log('Loaded image: ' + await element.getAttribute('src'));
949
1745
  # }
950
1746
  # await browser.close();
951
1747
  # })();
952
1748
  # ```
1749
+ #
1750
+ # ```python async
1751
+ # import asyncio
1752
+ # from playwright.async_api import async_playwright
1753
+ #
1754
+ # async def run(playwright):
1755
+ # chromium = playwright.chromium
1756
+ # browser = await chromium.launch()
1757
+ # page = await browser.new_page()
1758
+ # for current_url in ["https://google.com", "https://bbc.com"]:
1759
+ # await page.goto(current_url, wait_until="domcontentloaded")
1760
+ # element = await page.wait_for_selector("img")
1761
+ # print("Loaded image: " + str(await element.get_attribute("src")))
1762
+ # await browser.close()
1763
+ #
1764
+ # async def main():
1765
+ # async with async_playwright() as playwright:
1766
+ # await run(playwright)
1767
+ # asyncio.run(main())
1768
+ # ```
1769
+ #
1770
+ # ```python sync
1771
+ # from playwright.sync_api import sync_playwright
1772
+ #
1773
+ # def run(playwright):
1774
+ # chromium = playwright.chromium
1775
+ # browser = chromium.launch()
1776
+ # page = browser.new_page()
1777
+ # for current_url in ["https://google.com", "https://bbc.com"]:
1778
+ # page.goto(current_url, wait_until="domcontentloaded")
1779
+ # element = page.wait_for_selector("img")
1780
+ # print("Loaded image: " + str(element.get_attribute("src")))
1781
+ # browser.close()
1782
+ #
1783
+ # with sync_playwright() as playwright:
1784
+ # run(playwright)
1785
+ # ```
953
1786
  def wait_for_selector(selector, state: nil, timeout: nil)
954
1787
  raise NotImplementedError.new('wait_for_selector is not implemented yet.')
955
1788
  end
956
1789
 
957
1790
  # Waits for the given `timeout` in milliseconds.
958
- # Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
1791
+ #
1792
+ # Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be
1793
+ # flaky. Use signals such as network events, selectors becoming visible and others instead.
1794
+ #
959
1795
  #
960
1796
  # ```js
961
1797
  # // wait for 1 second
962
1798
  # await page.waitForTimeout(1000);
963
1799
  # ```
964
- # Shortcut for main frame's `frame.waitForTimeout(timeout)`.
1800
+ #
1801
+ # ```python async
1802
+ # # wait for 1 second
1803
+ # await page.wait_for_timeout(1000)
1804
+ # ```
1805
+ #
1806
+ # ```python sync
1807
+ # # wait for 1 second
1808
+ # page.wait_for_timeout(1000)
1809
+ # ```
1810
+ #
1811
+ # Shortcut for main frame's [`method: Frame.waitForTimeout`].
965
1812
  def wait_for_timeout(timeout)
966
1813
  raise NotImplementedError.new('wait_for_timeout is not implemented yet.')
967
1814
  end
968
1815
 
969
- # This method returns all of the dedicated WebWorkers associated with the page.
1816
+ # This method returns all of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)
1817
+ # associated with the page.
970
1818
  #
971
- # **NOTE** This does not contain ServiceWorkers
1819
+ # > NOTE: This does not contain ServiceWorkers
972
1820
  def workers
973
1821
  raise NotImplementedError.new('workers is not implemented yet.')
974
1822
  end
975
1823
 
1824
+ # @nodoc
1825
+ def after_initialize
1826
+ wrap_impl(@impl.after_initialize)
1827
+ end
1828
+
976
1829
  # @nodoc
977
1830
  def owned_context=(req)
978
- wrap_channel_owner(@channel_owner.owned_context=(req))
1831
+ wrap_impl(@impl.owned_context=(unwrap_impl(req)))
979
1832
  end
980
1833
 
1834
+ # -- inherited from EventEmitter --
981
1835
  # @nodoc
982
- def after_initialize
983
- wrap_channel_owner(@channel_owner.after_initialize)
1836
+ def on(event, callback)
1837
+ wrap_impl(@impl.on(unwrap_impl(event), unwrap_impl(callback)))
1838
+ end
1839
+
1840
+ # -- inherited from EventEmitter --
1841
+ # @nodoc
1842
+ def off(event, callback)
1843
+ wrap_impl(@impl.off(unwrap_impl(event), unwrap_impl(callback)))
1844
+ end
1845
+
1846
+ # -- inherited from EventEmitter --
1847
+ # @nodoc
1848
+ def once(event, callback)
1849
+ wrap_impl(@impl.once(unwrap_impl(event), unwrap_impl(callback)))
984
1850
  end
985
1851
  end
986
1852
  end