0

I know we can pass a javascript variable from an iframe to the parent frame like this:

If the parent and iframe were both on the same domain, we can call a function of the parent window:

iframe code:

window.postMe = "postMe value here";
window.parent.myFunction(postMe);

In the parent window, we can define a function like this:

function myFunction(postMe) {
    ((console&&console.log)||alert)("postMe= " + postMe);
}

And the code above logs the "postMe" value correctly.

But my question is how to modify this code in order to pass "postMe" from parent to the iframe?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Sara Ree
  • 3,417
  • 12
  • 48

1 Answers1

1

If you want to continue using the myFunction on the parent, you can have the parent function accept a callback passed by the child:

window.postMe = "postMe value here";
window.parent.myFunction(postMe, (response) => {
  console.log(response);
});
function myFunction(postMe, callback) {
  const val = "postMe= " + postMe;

  // do something with val in parent:
  ((console&&console.log)||alert)(val);

  // do something with val in child:
  callback(val);
}

See here for a live demonstration (can't be embedded as a Stack Snippet due to sandboxing issues):

https://jsfiddle.net/kc24onbq/

For one-way communication from the parent to the child, access the contentWindow of the iframe from the parent:

// child
function childFn(val) {
  console.log(val);
}
// parent
iFrameElement.contentWindow.childFn('foo');
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • unfortunately, I can't make it work (The first code) would you please explain it further? – Sara Ree Jun 05 '19 at 06:26
  • The first part is the code that is supposed to be on the iframe code and the second one should be on the parent, right? – Sara Ree Jun 05 '19 at 06:27
  • Wait ... I want to pass postMe from parent to iframe right? So I need the postMe as a variable inside the parent code... not in the iframe code... correct me if I'm wrong... – Sara Ree Jun 05 '19 at 06:50
  • You were asking how to modify your existing code, which had `postMe` in the iframe, and was sending the information to the parent, which is what I copied. You're free to send anything back to the child, see the `const val` line - whatever you put there will be sent to the iframe – CertainPerformance Jun 05 '19 at 06:55
  • Thank you... your code works great... Now I'm going to post another question on my issue... – Sara Ree Jun 05 '19 at 07:05
  • Can you please have a look at this discussion here: – Sara Ree Jun 05 '19 at 08:05
  • https://stackoverflow.com/questions/56456068/how-can-i-call-the-function-of-iframe-from-parent – Sara Ree Jun 05 '19 at 08:05