簡體   English   中英

如何從父級調用iframe函數?

[英]How can I call the function of iframe from parent?

如果父級和iframe都在同一域中,則可以從iframe調用父窗口的函數:

iframe代碼:

// here we call 'myFunction' which is a parent function

window.postMe = "postMe value here";
window.parent.myFunction(postMe);

在父窗口中,我們可以定義如下函數:

function myFunction(postMe) {
    ((console&&console.log)||alert)("postMe= " + postMe);
}

上面的代碼正確記錄了“ postMe”值。

但是我的問題是如何從父級調用iframe函數。

更清楚地說,我希望在我的iframe中使用以下代碼:

 function myFunction(postMe) {
        ((console&&console.log)||alert)("postMe= " + postMe);
    }

然后我想能夠調用myFunction(postMe); 在父母...

注意:由於某些原因,我無法選擇HTMLIFrameElement.contentWindowwindow.frames['name']類的iframe。

最終目標是:我想每次從父級傳遞到iframe時都要多次傳遞變量。 @CertainPerformance對此有一個解決方案,我無法使其正常運行。

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運行,而我不能調用該函數並從父級傳遞變量。

您可以將功能對象從iframe傳遞到父函數,然后從那里調用。

在父項上:

function tunnel(fn){
     fn('postMe');
}

在iframe上:

function myFunction(postMe) {
     ((console&&console.log)||alert)("postMe= " + postMe);
}
window.parent.tunnel(myFunction);

如果此時您的父文檔無法加載,請嘗試使用以下內容

var parentDocument = window.parent.document; 
$( parentDocument ).ready(function() { 
     window.parent.tunnel(myFunction); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM