Iframe postMessage
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
I have two pages where I'd like to send data from the first page to the other.
1st page has the following:
2nd page has a listener:
On 2nd page code is returning
1st page has the following:
React.useEffect(() => {
if (iframeRef.current?.contentWindow && code) {
iframeRef.current.contentWindow.postMessage(code, `*`); // Code is a string
}
}, [iframeRef.current?.contentWindow, code]);2nd page has a listener:
React.useEffect(() => {
function handleMessage(event: MessageEvent) {
// if (event.origin === window.location.origin + `/p/${slug}`) {
const receivedData = event.data;
setCode(receivedData);
// }
}
window.addEventListener("message", handleMessage);
return () => window.removeEventListener("message", handleMessage);
}, [code, setCode]);On 2nd page code is returning
null. Am I doing something wrong?1 Reply
Sphynx
Hey @Sun bear, did you find a solutino to this? I am also having troubles sending messages from an iframe to its parent window and could not find any solution yet... Would appreciate to hear how you handled the situation.