Skip to content

Commit 1aac61a

Browse files
committed
Add a new example on waitForEvent
The new example will work with a new tab to wait for the new page to be created before continuing on with the test. It also works with ControlOrMeta.
1 parent 9d9cc73 commit 1aac61a

File tree

1 file changed

+55
-2
lines changed

1 file changed

+55
-2
lines changed

docs/sources/next/javascript-api/k6-browser/browsercontext/waitforevent.md

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,65 @@ Waits for the event to fire and returns its value. If a predicate function has b
1818

1919
### Returns
2020

21-
| Type | Description |
22-
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
21+
| Type | Description |
22+
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2323
| `Promise<Page>` | A Promise that fulfills with a [page](https://grafana.com/docs/k6/<K6_VERSION>/javascript-api/k6-browser/page) object when the `page` event has been emitted. |
2424

2525
### Example
2626

27+
This API is useful when you want to wait for the new page to open after clicking on a link that opens in a new tab.
28+
29+
<CodeGroup labels={[]}>
30+
31+
```javascript
32+
import { browser } from 'k6/browser';
33+
34+
export const options = {
35+
scenarios: {
36+
ui: {
37+
executor: 'shared-iterations',
38+
options: {
39+
browser: {
40+
type: 'chromium',
41+
},
42+
},
43+
},
44+
},
45+
};
46+
47+
export default async function () {
48+
const page = await browser.newPage();
49+
50+
await page.goto('https://test.k6.io/');
51+
52+
await page.keyboard.down('ControlOrMeta');
53+
54+
// Open the link in a new tab with the help of the meta key.
55+
// Wait for the new page to be created.
56+
const browserContext = browser.context();
57+
const [newTab] = await Promise.all([
58+
browserContext.waitForEvent('page'),
59+
await page.locator('a[href="/my_messages.php"]').click(),
60+
]);
61+
62+
await page.keyboard.up('ControlOrMeta');
63+
64+
// Wait for the new page (tab) to load.
65+
await newTab.waitForLoadState('load');
66+
67+
// Take screenshots of each page.
68+
await page.screenshot({ path: `screenshot-page.png` });
69+
await newTab.screenshot({ path: `screenshot-newTab.png` });
70+
71+
await newTab.close();
72+
await page.close();
73+
}
74+
```
75+
76+
</CodeGroup>
77+
78+
Here's an example working with the predicate:
79+
2780
<CodeGroup labels={[]}>
2881

2982
```javascript

0 commit comments

Comments
 (0)