如何从父级调用iframe函数? [英] How can I call the function of iframe from parent?
问题描述
如果父级和iframe都在同一个域中,我们可以从iframe调用父窗口的函数:
If the parent and iframe were both on the same domain, we can call a function of the parent window from iframe:
iframe代码:
// 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);
}
上面的代码正确记录了"postMe"值.
And the code above logs the "postMe" value correctly.
但是我的问题是如何从父级调用iframe的功能.
But my question is how can I call the function of iframe from parent.
更清楚地说,我希望在我的iframe中使用以下代码:
To be more clear I want this code on my iframe:
function myFunction(postMe) {
((console&&console.log)||alert)("postMe= " + postMe);
}
然后我希望能够在父级上调用myFunction(postMe);
...
then I want to be able to call myFunction(postMe);
on the parent ...
注意:出于某些原因,我无法选择HTMLIFrameElement.contentWindow
或window.frames['name']
之类的iframe.
Note: I can't select the iframe like HTMLIFrameElement.contentWindow
or window.frames['name']
for some reasons.
最终目标是:我想每次从父级传递到iframe时都要多次传递变量. @CertainPerformance对此有一个解决方案,我无法使其正常工作.
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代码:
window.postMeToParent= "post me to parent";
window.parent.myFunction(postMeToParent, (response) => {
console.log(response);
});
父代码:
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);
}
问题在于它只能通过iframe运行,而我不能调用该函数并从父级传递变量.
The problem is it only can be run via iframe and I can't call the function and pass variables from parent.
推荐答案
您可以将功能对象从iframe传递到父函数,然后从那里调用.
You can pass the function object from iframe to parent function and invoke from there.
在父项上:
function tunnel(fn){
fn('postMe');
}
在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);
}
这篇关于如何从父级调用iframe函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!