I am opening a new window on my website where i have to wait till the user does a transaction on another website. I will then receive a postMessage call once the transaction is complete. How do i wait and only return once the even is fired?
This is a short example of the code:
async function anonTransaction() -> Promise {
const popupWindow = window.open("http://localhost:3000/")
let result = await new Promise((resolve, reject) => {
window.onmessage = (event) => {
if(event.origin !== "http://localhost:3000"){
reject()
}
else{
console.log("resolve");
resolve()
}
}});
}
/// on the opened website
let targetWebsite = window.opener;
targetWebsite.postMessage("message");
I am wondering, why don't you just execute your logic within onmessage?
window.onmessage = (event) => {
if(event.origin === "http://localhost:3000"){
// execute your logic here
myAsyncFunction();
}
};
If you really want a promise, you can try and create a global onmessage event listener which rejects or resolves a promise by saving the referrences to resolve and reject:
let resolve;
let reject;
let result = await new Promise((res, rej) => {
resolve = res;
reject = rej;
});
window.onmessage = (event) => {
if(event.origin !== "http://localhost:3000"){
if(reject) reject()
} else{
console.log("resolve");
if(resolve) resolve()
}
};