How to access parent Iframe from JavaScript

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

    Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

    The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

    /**
     * @param f, iframe or frame element
     * @return Window object inside the given frame
     * @effect will append f to document.body if f not yet part of the DOM
     * @see Window.frameElement
     * @usage myFrame.document = getFramedWindow(myFrame).document;
     */
    function getFramedWindow(f)
    {
        if(f.parentNode == null)
            f = document.body.appendChild(f);
        var w = (f.contentWindow || f.contentDocument);
        if(w && w.nodeType && w.nodeType==9)
            w = (w.defaultView || w.parentWindow);
        return w;
    }
    

提交回复
热议问题