Last active
March 20, 2025 02:56
-
-
Save kavinda1995/1fb85d632d88f5defd7e0c15bbdf068e to your computer and use it in GitHub Desktop.
Playwright Listen to window.PostMessages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
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