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?

1 Answer 1

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'); 
Sign up to request clarification or add additional context in comments.

7 Comments

unfortunately, I can't make it work (The first code) would you please explain it further?
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?
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...
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
Thank you... your code works great... Now I'm going to post another question on my issue...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.