How to access parent Iframe from JavaScript

后端 未结 9 1404
梦毁少年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:49

    you can use parent to access the parent page. So to access a function it would be:

    var obj = parent.getElementById('foo');
    
    0 讨论(0)
  • 2020-11-22 08:50
    // just in case some one is searching for a solution
    function get_parent_frame_dom_element(win)
    {
        win = (win || window);
        var parentJQuery = window.parent.jQuery;
        var ifrms = parentJQuery("iframe.upload_iframe");
        for (var i = 0; i < ifrms.length; i++)
        {
            if (ifrms[i].contentDocument === win.document)
                return ifrms[i];
        }
        return null;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题