How can I call the function of iframe from parent?

怎甘沉沦 提交于 2019-12-11 16:05:25

问题


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


来源:https://stackoverflow.com/questions/56456068/how-can-i-call-the-function-of-iframe-from-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!