Sara Ree
Sara Ree

Reputation: 3543

Pass a javascript variable from parent to the iframe

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?

Upvotes: 0

Views: 150

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

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');

Upvotes: 1

Related Questions