이 기사에서는 도메인 간 통신 문제를 해결하기 위한 html5 postMessage에 대한 자세한 설명을 소개하고 이를 모든 사람과 공유합니다.
렌더링
postmessage 구문 분석 HTML5는 안전한 출처 간 통신을 달성하기 위한 새로운 메커니즘 PostMessage를 제공합니다. 구문 otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow: IFRAME의 contentWindow 속성, 실행, window.open에서 반환된 창 개체 등 다른 창에 대한 참조 message: 다른 창으로 보낼 데이터 targetOrigin: Origin 속성을 통해 메시지 이벤트를 받을 수 있는 창을 지정합니다. 창에서 해당 값은 문자 *(무제한을 나타냄) 또는 URL 전송일 수 있습니다. 메시지와 동시에 전달되는 전송 가능한 객체의 문자열은 이러한 객체의 소유권이 메시지 수신자에게 전송됩니다. 일단 전송되면 소유권은 더 이상 유지되지 않습니다. element.addEventListener(event,fn,useCaption); click mouseenter mouseleave 콜백 함수 useCaption과 같은 세 가지 매개변수 이벤트 이벤트는 버블링 중인지 캡처 중인지 설명하는 데 사용됩니다. 기본값은 false이며 이는 버블 전달을 의미합니다. 값이 true이면 캡처되어 전달됩니다. 구현 방법
메인 인터페이스 main.html
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <meta name=viewport content=width=device-width,initial-scale=1.0> <meta http-equiv=X-UA -호환 가능한 콘텐츠=ie=edge> <title>교차 도메인 데이터 액세스</title> <script type=text/javascript> window.addEventListener('message',function(e){ console.log(e--->,e); const data = e.data; document.getElementById('main1').style.BackgroundColor=e.data; },false) </script></head><body> <div id=main1 style=width:200px;height:200px;margin:100px;border:solid 1px #000;> 나는 메인 인터페이스이고, iframe 전달을 받기를 기다리고 있습니다.</div> <div style=margin:100px;> iframe < iframe src= http://localhost:3000/iframe.html 너비=800px 높이=300px ></iframe> </div></body></html>iframe 인터페이스
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <meta name=viewport content=width=device-width,initial-scale=1.0> <meta http-equiv=X-UA -호환 가능한 콘텐츠=ie=edge> <title>문서</title> <style type=text/css> html,body{ height:100%; margin:0px; } </style></head> <body style=height:100%;> <div id=frame style=height:200px; width:200px; background-color:rgb(204, 204, 0) onclick=changeColor( )> 색상을 변경하려면 클릭하세요.</div> <script type=text/javascript> functionchangeColor(){ varframe = document.getElementById('frame'); var color=frame.style.BackgroundColor; if(color=='rgb(204, 102, 0)'){ color='rgb(204, 204, 0)' }else{ color='rgb(204,102,0 )'; } console.log(frame====>,frame); console.log(color,color); window.parent.postMessage(color,'*') } </script> </body></html>위 내용은 이 기사의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다. 또한 모든 분들이 VeVb Wulin Network를 지지해 주시길 바랍니다.