Skip to content

Instantly share code, notes, and snippets.

@kavinda1995
Last active March 20, 2025 02:56
Show Gist options
  • Save kavinda1995/1fb85d632d88f5defd7e0c15bbdf068e to your computer and use it in GitHub Desktop.
Save kavinda1995/1fb85d632d88f5defd7e0c15bbdf068e to your computer and use it in GitHub Desktop.
Playwright Listen to window.PostMessages
```
export const setupPostMessageListener = async (page: Page) => {
let messageList: any[] = [];
await page.exposeFunction('publishMessagesToE2E', (message: any) => {
messageList.push(message);
});
await page.evaluate(() => {
window.addEventListener('message', (event: MessageEvent) => {
const message = event.data;
window.publishMessagesToE2E(message);
});
}, messageList);
return {
messageList,
lastCalledWith: () => messageList.at(-1),
calledTimes: () => messageList.length,
clear: () => messageList = []
}
}
```
You can use this as
```
const postMessageListner = await setupPostMessageListener(page);
... Do your thing
console.log(postMessageListner.messageList);
console.log(postMessageListner.calledTimes());
```
Based and inspired by https://github.com/microsoft/playwright-python/issues/1019#issuecomment-966324492 answer and https://stackoverflow.com/a/79053725/6686446
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment