0

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:

  1. Create iframe for itemId = 1, store it in cache.
  2. Switch to itemId = 2 → mount its iframe, keep itemId = 1 iframe in cache (not in DOM).
  3. From itemId = 2, I want to send a message/event to the iframe of itemId = 1.

Is this possible? Anyway?

0

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.