[英]Call a jquery function to the parent page from iframe with regular javascript
我使用常规JavaScript创建了iframe。 在该iframe中,是Jquery函数和JQuery。 该代码可以像预期的那样在iframe中工作。 我想让父页面执行此功能,而不要在iframe中执行。 尽管创建iframe的代码可以在任何站点上运行,但iFrame和所有内容都是从同一域加载的。 例如,如果siteB,siteA运行了代码,则siteA&B可以创建iframe来访问siteZ的网站内容。
这是到目前为止我要在父页面中运行的iframe以外的代码:
<script>
$(document).ready(function(){
$().intad({
title: "blahblah",
url: "http://www.blah.com",
timeout: 30,
deplay: 2,
wait: 3,
closeable: true
});
});
</script>
我在iframe中尝试了以下方法:
<script>
$(document).ready(function(){
function intad(){
title: "blahblah",
url: "http://www.blah.com",
timeout: 30,
deplay: 2,
wait: 3,
closeable: true
});
});
</script>
这是从加载到父页面的代码中得出的:
<script>
parent.document.getElementById("RandomIdHere").contentWindow.intads();
</script>
在iFrame中,您需要将要调用的函数放在window
对象上,以便可以全局访问。
到那里后,您就可以从顶级HTML主页面执行iFrameDomElement.contentWindow.yourFunctionToCall()
。
编辑:
因此,要进一步分解,您的代码会遇到很多问题。 首先,什么是intad
? jQuery原型上的方法吗? 如果不是,则说明您做错了。 从根本上讲,这是您需要做的。
在您的主页中,从现在开始我将调用parent.html。
您需要这样的东西:
// this is a shorthand document ready function
$(function() {
// we will call this from the iframe
window.functionInParent = function() {
// do your work here
};
var iframe = document.createElement('iframe');
iframe.src = 'link/to/iframe/source';
// if you want to talk to the iframe from this parent page,
// use this to access the iframe's window object.
// just make sure that the function you try to call is on the
// window object of the iframe, just like we did with the function above.
var iframeWindow = iframe.contentWindow;
});
在您的iframe中,您需要这样的内容:
$(function() {
// your iframe's dom is ready - do stuff here
// once you are ready, call the parent function
top.functionInParent();
});
我希望这有帮助。 如果您需要进一步的帮助,请将您的工作(或几乎工作)代码放入jsfiddle中,以便我可以更好地对其进行研究。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.