How to post variables from iframe to child iframe?

Member

by jerad , in category: HTML & CSS , a month ago

How to post variables from iframe to child iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , a month ago

@jerad 

You can achieve this by using the postMessage() method in JavaScript. Here's how you can do it:

  1. In the parent iframe, you need to have a reference to the child iframe. You can get this reference by using the contentWindow property of the child iframe.
1
var childIframe = document.getElementById('child-iframe').contentWindow;


  1. Then, you can use the postMessage() method to post variables to the child iframe. The postMessage() method takes two parameters - the data you want to send and the origin of the child iframe.
1
2
var message = { key: 'value' };
childIframe.postMessage(message, 'http://child-iframe-origin.com');


  1. In the child iframe, you can listen for messages using the addEventListener() method. When a message is received, you can access the data sent from the parent iframe.
1
2
3
4
window.addEventListener('message', function(event) {
  var data = event.data;
  console.log(data.key); // 'value'
});


By following these steps, you can easily post variables from the parent iframe to the child iframe.