How can I call the function of iframe from parent?

2019-08-19 00:41发布

问题:

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

iframe code:

// here we call 'myFunction' which is a parent function

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 can I call the function of iframe from parent.

To be more clear I want this code on my iframe:

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

then I want to be able to call myFunction(postMe); on the parent ...

Note: I can't select the iframe like HTMLIFrameElement.contentWindow or window.frames['name'] for some reasons.

The final goal is: I want to pass a variable multiple times and every time I want from parent to the iframe. @CertainPerformance has a solution for this that I can't make it work.

iframe code:

window.postMeToParent= "post me to parent";
window.parent.myFunction(postMeToParent, (response) => {
  console.log(response);
});

parent code:

function myFunction(postMeToParent, callback) {
  const postMeToiframe= "post me to iframe";

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

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

The problem is it only can be run via iframe and I can't call the function and pass variables from parent.

回答1:

You can pass the function object from iframe to parent function and invoke from there.

On the parent:

function tunnel(fn){
     fn('postMe');
}

On the iframe:

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

If your parent document will not be loaded at that point, try using below

var parentDocument = window.parent.document; 
$( parentDocument ).ready(function() { 
     window.parent.tunnel(myFunction); 
}