How to pass a value from iframe to the parent?

Member

by deron , in category: Javascript , 11 days ago

How to pass a value from iframe to the parent?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 11 days ago

@deron 

To pass a value from an iframe to the parent document, you can use the window.postMessage() method in JavaScript.


Here's an example of how to do this:

  1. In the iframe document, you can send a message to the parent document using the postMessage() method. For example:
1
2
var message = 'Hello parent!';
window.parent.postMessage(message, '*');


  1. In the parent document, you can listen for messages from the iframe using the window.addEventListener() method. For example:
1
2
3
4
5
6
7
window.addEventListener('message', function(event) {
  // Check that the message is coming from the iframe
  if (event.source == iframe.contentWindow) {
    // Do something with the message
    console.log('Message from iframe: ' + event.data);
  }
});


Make sure to replace 'Hello parent!' with the value you want to pass from the iframe to the parent. This code snippet assumes that the iframe and parent are on the same domain. If they are on different domains, some additional setup may be necessary for security reasons.