How to pass argument from iframe to parent?

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

How to pass argument from iframe to parent?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 7 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.

Related Threads:

How to pass a value from iframe to the parent?
How to pass next as an argument on mocha test?
How to pass an argument to event handler in tkinter?
How to pass object type argument in query in graphql?
How to get parent iframe id in javascript?
How to resize parent window size from iframe?