Programming

JavaScript에서 부모 Iframe에 액세스하는 방법

procodes 2020. 6. 5. 22:22
반응형

JavaScript에서 부모 Iframe에 액세스하는 방법


글쎄, 같은 도메인 페이지를 호출하는 IFrame이 있습니다. 내 문제는 JavaScript라고하는이 페이지 에서이 부모 Iframe의 일부 정보에 액세스하려고한다는 것입니다. 이 Iframe에 어떻게 액세스 할 수 있습니까?

세부 정보 : Windows 환경을 프로그래밍하고 있기 때문에이 페이지와 같은 여러 Iframe이 있으며 동일한 페이지를로드 할 수 있습니다. 나는이 Iframe을 닫으려고하는데, 그래서 나는 그 안에서 어떤 것을 닫아야하는지 알아야합니다. 이 Iframe에 대한 참조를 유지하는 배열이 있습니다.

편집 : iframe이 동적으로 생성됩니다


또한 이름과 ID를 같은 값으로 설정할 수 있습니다

<iframe id="frame1" name="frame1" src="any.html"></iframe>

자식 페이지 내에서 다음 코드를 사용할 수 있습니다.

parent.document.getElementById(window.name);

window.frameElement액자 페이지에서 간단히 전화 하십시오. 페이지가 프레임에없는 경우 frameElement가 될 것이다 null.

다른 방법 (프레임 안에 창 요소를 넣는 것은 쉽지 않음)이지만 완전성을 위해 :

/**
 * @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;
}

postMessage API를 사용하는 것이 좋습니다 .

iframe에서 전화 :

window.parent.postMessage({message: 'Hello world'}, 'http://localhost/');

페이지에서 iframe을 포함 시키면 다음과 같은 이벤트를들을 수 있습니다.

window.addEventListener('message', function(event) {
      if(event.origin === 'http://localhost/')
      {
        alert('Received message: ' + event.data.message);
      }
      else
      {
        alert('Origin not allowed!');
      }

    }, false);

그건 그렇고, iframe뿐만 아니라 다른 창으로 전화를 걸 수도 있습니다.

John Resigs 블로그의 postMessage API에 대한 자세한 내용은 여기를 참조하십시오.


오래된 질문이지만 방금 동일한 문제가 발생하여 iframe을 얻는 방법을 찾았습니다. 단순히 부모 창의 frames [] 배열을 반복하고 코드가 실행되는 창에 대해 각 프레임의 contentWindow를 테스트하는 것입니다. 예:

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

또는 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.


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

var obj = parent.getElementById('foo');

Once id of iframe is set, you can access iframe from inner document as shown below.

var iframe = parent.document.getElementById(frameElement.id);

Works well in IE, Chrome and FF.


Maybe just use

window.parent

into your iframe to get the calling frame / windows. If you had multiple calling frame, you can use

window.top

Try this, in your parent frame set up you IFRAMEs like this:

<iframe id="frame1" src="inner.html#frame1"></iframe>
<iframe id="frame2" src="inner.html#frame2"></iframe>
<iframe id="frame3" src="inner.html#frame3"></iframe>

Note that the id of each frame is passed as an anchor in the src.

then in your inner html you can access the id of the frame it is loaded in via location.hash:

<button onclick="alert('I am frame: ' + location.hash.substr(1))">Who Am I?</button>

then you can access parent.document.getElementById() to access the iframe tag from inside the iframe


// 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;
}

참고URL : https://stackoverflow.com/questions/935127/how-to-access-parent-iframe-from-javascript

반응형