Programming > JSP/HTML/JSTL

다른 도메인의 iframe 높이조절 (cross domain iframe height resize)

다른 도메인의 내용을 iframe에 읽어 사용하기

1) 부모화면 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script type="text/javascript">
    window.addEventListener('message',function(e){
        console.log(e.origin);
               var doc = document.getElementById("myfrm");
        doc.style.height = e.data.height + 'px';
              //doc.style.width = e.data.width + 'px';
    }) ;
</script>
</head>
<body>

    <div>
    IFRAME
    </div>
    <hr/>
   
    <iframe id="myfrm" style="width:100%;"
        src="http://192.168.11.103:8888"
        framespacing="0"
        frameborder="0"
        scrolling="no" >
       
        No Data !!
    </iframe>

</body>
</html>
 

2) 요청되는 화면

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script language='JavaScript' type='text/javascript'>
function init(){
    var frm = document.getElementById("myframe");
    pageheight = frm.offsetHeight;
    pagewidth = frm.offsetWidth;
   
        // 두번째 파라메터(targetOrigin) 에 * 를 넣으면 모든 도메인 허용
    window.parent.postMessage({height:pageheight, width:pagewidth}, 'http://192.168.11.103:8080/');
        // window.parent.postMessage({height:pageheight, width:pagewidth}, '*');
}
function appendData(){
    var frm = document.getElementById("myframe");
    frm.innerHTML += "<p>문장을 추가합니다.</p>";
    init();
}
</script>

</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onload="init();">

    <div id='myframe'>
        <button onclick="appendData()">Click me</button>
        <p>우리나라 대한민국</p>
    </div>

</body>
</html>