Middle
Kuidas toimub andmete vahetamine iframe'i ja põhilehe vahel?
sobes.tech AI
Vastus AI-lt
There are several methods of data exchange:
-
PostMessage API:
- The main and secure way.
- Allows sending messages between windows (iframe/parent, different windows/tabs) from different domains.
- It is important to specify the expected
originto prevent XSS attacks.
// Sending from parent window to iframe const iframeEl = document.getElementById('my-iframe'); iframeEl.contentWindow.postMessage('Hello from parent!', 'https://trusted-domain.com'); // Receiving in iframe window.addEventListener('message', function(event) { if (event.origin !== 'https://parent-domain.com') { return; // Check sender } console.log('Message received in iframe:', event.data); }); // Sending from iframe to parent window window.parent.postMessage('Hello from iframe!', 'https://parent-domain.com'); // Receiving in parent window window.addEventListener('message', function(event) { if (event.origin !== 'https://iframe-domain.com') { return; // Check sender } console.log('Message received in parent:', event.data); }); -
Access to
windowobject (only for Same-Origin):- If iframe and parent page are on the same domain (Same-Origin Policy), they can directly access each other's
windowobjects.
// In parent window const iframeEl = document.getElementById('my-iframe'); const iframeWindow = iframeEl.contentWindow; iframeWindow.someVariable = 'Value from parent'; iframeWindow.someFunction(); // In iframe const parentWindow = window.parent; console.log(parentWindow.someVariable); parentWindow.someOtherFunction(); - If iframe and parent page are on the same domain (Same-Origin Policy), they can directly access each other's
-
URL hash (
#):- Simple but limited method.
- Can pass small data by changing the hash in iframe URL.
- Hash changes do not reload the page.
- Requires monitoring hash changes (e.g., via
hashchangeevent).
// In parent window, to change iframe hash const iframeEl = document.getElementById('my-iframe'); iframeEl.contentWindow.location.hash = 'data=some_value'; // In iframe, to read hash window.addEventListener('hashchange', function() { const hash = window.location.hash; console.log('Hash changed:', hash); // Parse data from hash }); -
Changing
location.href(less preferred):- Passing data by changing iframe URL and reloading it.
- Not suitable for frequent exchanges.
-
Shared storage (Same-Origin):
localStorageandsessionStorage.- If iframe and parent are on the same domain, they can use the same storage.
// In parent window localStorage.setItem('sharedData', JSON.stringify({ value: 'Example' })); // In iframe const data = JSON.parse(localStorage.getItem('sharedData')); console.log('Data from localStorage:', data);
The choice of method depends on security policies (Same-Origin Policy) and the volume/type of data transmitted. PostMessage is the most flexible and secure solution for cross-domain communication.