I’m using Nextjs and on my laptop the code is working as intended
when accessing the page from my Iphone it didn’t load
I’m using it to send data between iframes on two different sites
on the Nextjs project
useEffect(() => {
const handleLoad = () => {
if (iframeRef.current) {
iframeRef.current.contentWindow.postMessage(
{ data },
process.env.IFRAME_LINK
);
}
};
if (iframeRef.current) {
iframeRef.current.addEventListener('load', handleLoad);
}
return () => {
if (iframeRef.current) {
iframeRef.current.removeEventListener('load', handleLoad);
}
};
}, [iframeRef.current]);
Again on a pc/laptop this working
The Iframe site code (Vite React)
useEffect(() => {
const handleMessage = (event) => {
const parentURL = import.meta.env.PARENT_URL;
if (event.origin !== parentURL) return;
let { data } = event.data;
console.log('received');
setUserData(data);
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
2
Answers
I tried the same just a change I did is
I Used
loadmetadata
instead ifload
and instead of usingimport.meta.env.PARENT_URL;
I used a static url.You can console or put an alert before your
if (event.origin !== parentURL) return;
for parent url it might be stuck there.
Initially it happend with me as well.
This could be due to one of the reasons below:
Ensure the iframe is loaded before sending the message in the parent (next.js):
iframe (Vite React):
Check the message origin to allow only trusted sources:
Additional Tips:
Test with hardcoded origins (replace environment variables temporarily).
Add a slight delay in postMessage for Safari:
setTimeout(() => iframeRef.current?.contentWindow?.postMessage({ data }, ‘https://your-iframe-site.com’), 100);