How to pass argument from iframe to parent?

by scotty_walker , in category: Third Party Scripts , 4 months ago

How to pass argument from iframe to parent?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 4 months ago

@scotty_walker 

To pass an argument from an iframe to its parent, you can use the postMessage method in JavaScript. Here's how you can do it:

  1. In the child iframe:
1
2
// Send a message to the parent window
window.parent.postMessage('Hello parent!', '*');


  1. In the parent window:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Add an event listener to listen for messages from the child iframe
window.addEventListener('message', function(event) {
  // Check the origin of the message to prevent security issues
  if (event.origin !== 'https://example.com') {
    return;
  }
  
  // Log the message received from the child iframe
  console.log('Message received from child:', event.data);
});


Make sure to replace 'https://example.com' with the actual origin of the child iframe. This will ensure that the message is only received from a trusted source.


By using the postMessage method, you can securely pass arguments from an iframe to its parent window in a controlled manner.