programing

iframe과 상위 사이트 간의 통신 방법

bestcode 2022. 11. 8. 21:50
반응형

iframe과 상위 사이트 간의 통신 방법

iframe의 웹사이트가 같은 도메인에 있는 것은 아니지만 둘 다 내 것이므로 서로 통신하고 싶다.iframe및 부모 사이트.가능합니까?

도메인이 다른 경우 메서드를 호출하거나 iframe의 내용 문서에 직접 액세스할 수 없습니다.

교차 문서 메시징을 사용해야 합니다.

부모 -> iframe

예를 들어 상단 창에 다음과 같이 표시됩니다.

myIframe.contentWindow.postMessage('hello', '*');

및 iframe:

window.onmessage = function(e) {
    if (e.data == 'hello') {
        alert('It works!');
    }
};

iframe -> 부모

예를 들어 상단 창에 다음과 같이 표시됩니다.

window.onmessage = function(e) {
    if (e.data == 'hello') {
        alert('It works!');
    }
};

및 iframe:

window.top.postMessage('hello', '*')

2018년 및 최신 브라우저에서는 iframe에서 부모 창으로 커스텀 이벤트를 전송할 수 있습니다.

iframe:

var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)

부모:

window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
  console.log(e.detail) // outputs: {foo: 'bar'}
}

PS: 물론, 같은 방법으로 이벤트를 반대 방향으로 송신할 수 있습니다.

document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)

이 라이브러리는 html5 postMessage 및 resize+displays https://github.com/ternarylabs/porthole 를 사용하는 레거시 브라우저를 지원합니다.

편집: 현재 2014년에는 IE6/7 사용률이 상당히 낮습니다. IE8 및 기타 지원도 마찬가지입니다.postMessage그래서 저는 이제 그걸 쓰라고 제안합니다.

https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

사용하다event.source.window.postMessage송신자에게 반송할 수 있습니다.

Iframe에서

window.top.postMessage('I am Iframe', '*')
window.onmessage = (event) => {
    if (event.data === 'GOT_YOU_IFRAME') {
        console.log('Parent received successfully.')
    }
}

그럼 부모님께서 말대답하세요.

window.onmessage = (event) => {
    event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}

window.top부동산은 당신이 필요한 것을 줄 수 있어야 합니다.

예.

alert(top.location.href)

http://cross-browser.com/talk/inter-frame_comm.html 를 참조해 주세요.

를 사용할 수도 있습니다.

postMessage(message, '*');

언급URL : https://stackoverflow.com/questions/9153445/how-to-communicate-between-iframe-and-the-parent-site

반응형