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.