How to access parent Iframe from JavaScript

后端 未结 9 1528
梦毁少年i
梦毁少年i 2020-11-22 07:50

Well, I have an IFrame, which calls a same domain page. My problem is that I want to access some information from this parent Iframe from this called page (from JavaScript).

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 08:54

    Old question, but I just had this same issue and found a way to get the iframe. It's simply a matter of iterating through the parent window's frames[] array and testing each frame's contentWindow against the window in which your code is running. Example:

    var arrFrames = parent.document.getElementsByTagName("IFRAME");
    for (var i = 0; i < arrFrames.length; i++) {
      if (arrFrames[i].contentWindow === window) alert("yay!");
    }
    

    Or, using jQuery:

    parent.$("iframe").each(function(iel, el) {
      if(el.contentWindow === window) alert("got it");
    });
    

    This method saves assigning an ID to each iframe, which is good in your case as they are dynamically created. I couldn't find a more direct way, since you can't get the iframe element using window.parent - it goes straight to the parent window element (skipping the iframe). So looping through them seems the only way, unless you want to use IDs.

提交回复
热议问题