[英]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.