Skip to content

Commit 9a4d690

Browse files
authored
cherry-pick(release-1.9): add java snippets to the examples in guides (#5638) (#5660)
* docs: more clarity in the attribute selectors (#5621) * docs: add java snippets to the examples in guides (#5638) * docs: docs typos (#5658)
1 parent 948e658 commit 9a4d690

22 files changed

+1245
-25
lines changed

docs/src/assertions.md

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,18 @@ text content of an element. These APIs can be used in your test assertions.
88

99
<!-- TOC -->
1010

11-
1211
## Text content
1312

1413
```js
1514
const content = await page.textContent('nav:first-child');
1615
expect(content).toBe('home');
1716
```
1817

18+
```java
19+
String content = page.textContent("nav:first-child");
20+
assertEquals("home", content);
21+
```
22+
1923
```python async
2024
content = await page.text_content("nav:first-child")
2125
assert content == "home"
@@ -37,6 +41,11 @@ const text = await page.innerText('.selected');
3741
expect(text).toBe('value');
3842
```
3943

44+
```java
45+
String text = page.innerText(".selected");
46+
assertEquals("value", text);
47+
```
48+
4049
```python async
4150
text = await page.inner_text(".selected")
4251
assert text == "value"
@@ -58,6 +67,11 @@ const alt = await page.getAttribute('input', 'alt');
5867
expect(alt).toBe('Text');
5968
```
6069

70+
```java
71+
String alt = page.getAttribute("input", "alt");
72+
assertEquals("Text", alt);
73+
```
74+
6175
```python async
6276
checked = await page.get_attribute("input", "alt")
6377
assert alt == "Text"
@@ -75,6 +89,11 @@ const checked = await page.isChecked('input');
7589
expect(checked).toBeTruthy();
7690
```
7791

92+
```java
93+
boolean checked = page.isChecked("input");
94+
assertTrue(checked);
95+
```
96+
7897
```python async
7998
checked = await page.is_checked("input")
8099
assert checked
@@ -96,6 +115,11 @@ const content = await page.$eval('nav:first-child', e => e.textContent);
96115
expect(content).toBe('home');
97116
```
98117

118+
```java
119+
Object content = page.evalOnSelector("nav:first-child", "e => e.textContent");
120+
assertEquals("home", content);
121+
```
122+
99123
```python async
100124
content = await page.eval_on_selector("nav:first-child", "e => e.textContent")
101125
assert content == "home"
@@ -117,6 +141,11 @@ const html = await page.innerHTML('div.result');
117141
expect(html).toBe('<p>Result</p>');
118142
```
119143

144+
```java
145+
String html = page.innerHTML("div.result");
146+
assertEquals("<p>Result</p>", html);
147+
```
148+
120149
```python async
121150
html = await page.inner_html("div.result")
122151
assert html == "<p>Result</p>"
@@ -138,6 +167,11 @@ const visible = await page.isVisible('input');
138167
expect(visible).toBeTruthy();
139168
```
140169

170+
```java
171+
boolean visible = page.isVisible("input");
172+
assertTrue(visible);
173+
```
174+
141175
```python async
142176
visible = await page.is_visible("input")
143177
assert visible
@@ -156,7 +190,12 @@ assert visible
156190

157191
```js
158192
const enabled = await page.isEnabled('input');
159-
expect(visible).toBeTruthy();
193+
expect(enabled).toBeTruthy();
194+
```
195+
196+
```java
197+
boolean enabled = page.isEnabled("input");
198+
assertTrue(enabled);
160199
```
161200

162201
```python async
@@ -198,6 +237,25 @@ const length = await page.$$eval('li.selected', (items) => items.length);
198237
expect(length === 3).toBeTruthy();
199238
```
200239

240+
```java
241+
// Assert local storage value
242+
Object userId = page.evaluate("() => window.localStorage.getItem('userId')");
243+
assertNotNull(userId);
244+
245+
// Assert value for input element
246+
page.waitForSelector("#search");
247+
Object value = page.evalOnSelector("#search", "el => el.value");
248+
assertEquals("query", value);
249+
250+
// Assert computed style
251+
Object fontSize = page.evalOnSelector("div", "el => window.getComputedStyle(el).fontSize");
252+
assertEquals("16px", fontSize);
253+
254+
// Assert list length
255+
Object length = page.evalOnSelectorAll("li.selected", "items => items.length");
256+
assertEquals(3, length);
257+
```
258+
201259
```python async
202260
# Assert local storage value
203261
user_id = page.evaluate("() => window.localStorage.getItem('user_id')")
@@ -245,4 +303,4 @@ assert length == 3
245303
- [`method: Frame.evalOnSelectorAll`]
246304
- [`method: ElementHandle.evalOnSelector`]
247305
- [`method: ElementHandle.evalOnSelectorAll`]
248-
- [EvaluationArgument]
306+
- [EvaluationArgument]

docs/src/auth.md

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,17 @@ await page.click('text=Submit');
3636
// Verify app is logged in
3737
```
3838

39+
```java
40+
Page page = context.newPage();
41+
page.navigate("https://github.com/login");
42+
// Interact with login form
43+
page.click("text=Login");
44+
page.fill("input[name='login']", USERNAME);
45+
page.fill("input[name='password']", PASSWORD);
46+
page.click("text=Submit");
47+
// Verify app is logged in
48+
```
49+
3950
```python async
4051
page = await context.new_page()
4152
await page.goto('https://github.com/login')
@@ -88,6 +99,16 @@ const storageState = JSON.parse(process.env.STORAGE);
8899
const context = await browser.newContext({ storageState });
89100
```
90101

102+
```java
103+
// Save storage state and store as an env variable
104+
String storage = context.storageState();
105+
System.getenv().put("STORAGE", storage);
106+
107+
// Create a new context with the saved storage state
108+
BrowserContext context = browser.newContext(
109+
new Browser.NewContextOptions().withStorageState(storage));
110+
```
111+
91112
```python async
92113
import json
93114
import os
@@ -150,6 +171,23 @@ await context.addInitScript(storage => {
150171
}, sessionStorage);
151172
```
152173

174+
```java
175+
// Get session storage and store as env variable
176+
String sessionStorage = (String) page.evaluate("() => JSON.stringify(sessionStorage");
177+
System.getenv().put("SESSION_STORAGE", sessionStorage);
178+
179+
// Set session storage in a new context
180+
String sessionStorage = System.getenv("SESSION_STORAGE");
181+
context.addInitScript("(storage => {\n" +
182+
" if (window.location.hostname === 'example.com') {\n" +
183+
" const entries = JSON.parse(storage);\n" +
184+
" Object.keys(entries).forEach(key => {\n" +
185+
" window.sessionStorage.setItem(key, entries[key]);\n" +
186+
" });\n" +
187+
" }\n" +
188+
"})(" + sessionStorage + ")");
189+
```
190+
153191
```python async
154192
import os
155193
# Get session storage and store as env variable
@@ -199,8 +237,6 @@ manual intervention. Persistent authentication can be used to partially automate
199237
MFA scenarios.
200238

201239
### Persistent authentication
202-
Web browsers use a directory on disk to store user history, cookies, IndexedDB
203-
and other local state. This disk location is called the [User data directory](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md).
204240

205241
Note that persistent authentication is not suited for CI environments since it
206242
relies on a disk location. User data directories are specific to browser types
@@ -216,6 +252,22 @@ const context = await chromium.launchPersistentContext(userDataDir, { headless:
216252
// Execute login steps manually in the browser window
217253
```
218254

255+
```java
256+
import com.microsoft.playwright.*;
257+
258+
public class Example {
259+
public static void main(String[] args) {
260+
try (Playwright playwright = Playwright.create()) {
261+
BrowserType chromium = playwright.chromium();
262+
Path userDataDir = Paths.get("/path/to/directory");
263+
BrowserContext context = chromium.launchPersistentContext(userDataDir,
264+
new BrowserType.LaunchPersistentContextOptions().withHeadless(false));
265+
// Execute login steps manually in the browser window
266+
}
267+
}
268+
}
269+
```
270+
219271
```python async
220272
import asyncio
221273
from playwright.async_api import async_playwright
@@ -246,4 +298,4 @@ with sync_playwright() as p:
246298

247299
### API reference
248300
- [BrowserContext]
249-
- [`method: BrowserType.launchPersistentContext`]
301+
- [`method: BrowserType.launchPersistentContext`]

docs/src/ci.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,11 @@ Suggested configuration
8383
});
8484
```
8585

86+
```java
87+
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
88+
.withArgs(Arrays.asList("--disable-dev-shm-usage")));
89+
```
90+
8691
```python async
8792
browser = await playwright.chromium.launch(
8893
args=['--disable-dev-shm-usage']
@@ -233,6 +238,19 @@ const { chromium } = require('playwright');
233238
const browser = await chromium.launch({ chromiumSandbox: false });
234239
```
235240

241+
```java
242+
import com.microsoft.playwright.*;
243+
244+
public class Example {
245+
public static void main(String[] args) {
246+
try (Playwright playwright = Playwright.create()) {
247+
BrowserType chromium = playwright.chromium();
248+
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withChromiumSandbox(false));
249+
}
250+
}
251+
}
252+
```
253+
236254
```python async
237255
browser = await playwright.chromium.launch(chromiumSandbox=False)
238256
```
@@ -319,6 +337,20 @@ const { chromium } = require('playwright');
319337
const browser = await chromium.launch({ headless: false });
320338
```
321339

340+
```java
341+
// Works across chromium, firefox and webkit
342+
import com.microsoft.playwright.*;
343+
344+
public class Example {
345+
public static void main(String[] args) {
346+
try (Playwright playwright = Playwright.create()) {
347+
BrowserType chromium = playwright.chromium();
348+
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withHeadless(false));
349+
}
350+
}
351+
}
352+
```
353+
322354
```python async
323355
import asyncio
324356
from playwright.async_api import async_playwright

docs/src/cli.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,27 @@ const { chromium } = require('playwright');
9191
})();
9292
```
9393

94+
```java
95+
// FIXME
96+
import com.microsoft.playwright.*;
97+
98+
public class Example {
99+
public static void main(String[] args) {
100+
try (Playwright playwright = Playwright.create()) {
101+
BrowserType chromium = playwright.chromium();
102+
// Make sure to run headed.
103+
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withHeadless(false));
104+
// Setup context however you like.
105+
BrowserContext context = browser.newContext(/* pass any options */);
106+
context.route("**/*", route -> route.resume());
107+
// Pause the page, and start recording manually.
108+
Page page = context.newPage();
109+
page.pause();
110+
}
111+
}
112+
}
113+
```
114+
94115
```python async
95116
import asyncio
96117
from playwright.async_api import async_playwright

0 commit comments

Comments
 (0)