iframe에서 부모 윈도우로 데이터 보내기
https://htmldom.dev/communication-between-an-iframe-and-its-parent-window
// Called from the iframe
window.parent.postMessage(message, '*');
여기서 메시지는 문자열입니다. 여러 데이터를 보내려면 JSON으로 인코딩 할 수 있습니다.
// Called from the iframe
const message = JSON.stringify({
message: 'Hello from iframe',
date: Date.now(),
});
window.parent.postMessage(message, '*');
페이지에서 하위 iframe으로 데이터 보내기
// Called from the page
frameEle.contentWindow.postMessage(message, '*');
여기서 frameEle은 iframe 요소를 나타냅니다.
전송 된 데이터 수신
iframe 또는 메인 페이지에서 메시지 이벤트를 수신하여 전송 된 데이터를 수신 할 수 있습니다.
window.addEventListener('message', function(e) {
// Get the sent data
const data = e.data;
// If you encode the message in JSON before sending them,
// then decode here
// const decoded = JSON.parse(data);
});
팁
다른 iframe에서 메시지를 보내거나 받는 경우 메시지의 출처를 나타내는 매개 변수를 포함 할 수 있습니다.
// From a child iframe
const message = JSON.stringify({
channel: 'FROM_FRAME_A',
...
});
window.parent.postMessage(message, '*');
그런 다음 기본 페이지에서 매개 변수를 보고 메시지를 구별 할 수 있습니다.
window.addEventListener('message', function(e) {
const data = JSON.parse(e.data);
// Where does the message come from
const channel = data.channel;
});
등록된 댓글이 없습니다.