11. How to communicate between window and it's iframe?

Element HTML iframe allows to run another website inside your website.

Communication between them is possible on two ways.

If website-parent (parent) and iframe app shares same domain, they share localStorage as well. In this case it's possible to listen to localStorage changes and to react to them.

//parent const dataToSend = { message: "This is a message." }; localStorage.setItem("messageToIframe", JSON.stringify(dataToSend)); //iframe window.addEventListener("storage", function (event) { if (event.key === "messageToIframe") { const dataReceived = JSON.parse(event.newValue); console.log(dataReceived.message); //This is a message. } });

Such communication works two-ways - both iframe and parent can be sender or recipient.

Another way, safe when it comes to CORS issues, is postMessage mechanism. It allows to keep domain checks for safety on both sides.

postMessage accepts as arguments a message and targetOrigin - it's a domain, which iframe has to be hosted on to receive a message. Marking origin as * makes the domain unimportant.

//parent localStorage.setItem("messageToIframe", JSON.stringify(dataToSend)); const dataToSend = { message: "This is a message." }; iframe.contentWindow.postMessage(messageData, "*"); //iframe window.addEventListener("message", function (event) { if (event.origin === "http://localhost:8080") { //origin check const dataReceived = JSON.parse(event.data); console.log(dataReceived.message); //This is a message. } });

Similar to localStorage listener, this communication works two-ways. To change it, all you have to do is to set eventListener to message in parent's window, and in an iframe you'd have to send messages to parent (window.parent).

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.