Middle+
How does an embedded iframe (for example, a map or video) interact with the main site's cookies? How to organize communication between different sources?
sobes.tech AI
Answer from AI
An embedded iframe, for example with a map or video, loads content from another source (domain, protocol, port), and the browser isolates it from the main site according to security policy (Same-Origin Policy).
Cookies interaction:
- Cookies are set and accessible only to the domain that created them.
- An iframe cannot directly read or modify cookies of the main site if they are from different domains.
- If the iframe and the main site are on the same domain, cookies are accessible to both.
Communication between different sources:
- To exchange data between an iframe and the main site, the
window.postMessagemechanism is used. - This API allows safe sending of messages between windows/frames, even if they are from different domains.
Example of using postMessage:
// In the main window
const iframe = document.getElementById('myIframe');
iframe.contentWindow.postMessage('Hello iframe', 'https://iframe-domain.com');
window.addEventListener('message', event => {
if (event.origin === 'https://iframe-domain.com') {
console.log('Message from iframe:', event.data);
}
});
// In the iframe
window.addEventListener('message', event => {
if (event.origin === 'https://main-site.com') {
console.log('Message from main site:', event.data);
event.source.postMessage('Hello main site', event.origin);
}
});
Thus, cookies are isolated by domains, and postMessage is used for data exchange between the iframe and the main site.