I’m working on a React app where I need to manage multiple iframes dynamically. Each iframe is created only once and stored in a cache (Map/Ref) for reuse. At any given time, only the selected iframe should be mounted in the DOM. Other iframes remain cached (not attached to the DOM).
My question is:
Is there a way to send messages/events (using postMessage or similar) to an iframe that is stored in cache but not currently mounted in the DOM? Currently i'm getting contentWindow value as null
Example workflow:
- Create iframe for itemId = 1, store it in cache.
- Switch to itemId = 2 → mount its iframe, keep itemId = 1 iframe in cache (not in DOM).
- From itemId = 2, I want to send a message/event to the iframe of itemId = 1.
Is this possible? Anyway?
1 Answer 1
No, a detached <iframe> has no attached window (specs).
onmessage = (evt) => console.log(evt.data);
setTimeout(() => {
document.querySelector("iframe").remove();
}, 1000);
<iframe srcdoc="<script>
setInterval(() => {
parent.postMessage('from frame', '*');
console.log('in frame');
}, 200);
</script>"></iframe>
When you attach it again, a new window is created:
setTimeout(() => {
const frame = document.querySelector("iframe");
frame.remove();
document.body.append(frame);
}, 1000);
<iframe srcdoc="<body><script>
document.body.textContent = Math.random();
</script></body>"></iframe>
Comments
Explore related questions
See similar questions with these tags.