devlog_zz

iframe, postMessage 본문

Front End

iframe, postMessage

YJ_SW 2021. 3. 12. 14:18
728x90

iframe

iframe이란?

HTML Inline Frame

하나의 HTML문서내에서 다른 HTML문서를 보여주고자 할때 사용

웹 페이지 안에 어떠한 제한 없이 또 다른 하나의 웹 페이지를 삽입할 수 있음

이번 프로젝트에서는 앱 안에서 두개의 다른 웹페이지를 연동하며 데이터를 주고받기 위해 iframe을 사용했다.

postMessage

페이지와 페이지 안의 iframe 간의 통신에 사용

postMessage 전송할 때

 window.parent.postMessage({'messageId':'NEW-01'}, '*')

postMessage 수신할 때

window.addEventListener('message', (e)=>{
        if(e.data.messageId === 'NEW-01'){
            // 수신 후 처리
        }
    });

iframe 안보이는 오류

기존코드

 <iframe ref={iframe} id="newFrame" src="http://localhost:3000/" width="100%" height="100%" frameborder="0"></iframe> 

해결한 코드

<iframe ref={iframe} id="newFrame" src="http://localhost:3000/" width="100%" height="100%" style={{border:'none'}}/>

border가 회색으로 처리되어 frameborder="0"으로 지정했다가 iframe이 안보여서
style={{border:'none'}} 으로 주어 해결하였다.

활용 예시 코드

보이게 안보이게 화면 전환

App.js

const App = () => {
  const [viewMode, setViewMode] = useState('initView')
  const [iframe, setIframe] = useState(null)

  return (
    <div className="App" style={{width:'100%', height:'100%'}}>
      <Newframe viewMode={viewMode} setIframe={setIframe}/>
    </div>
  )
}

const Newframe = (props) => {
  const iframe = useRef()
  useEffect(()=>{
    props.setIframe(iframe.current)
  },[])
  return (
    <div className="content" style={{display:props.viewMode==='newframe'?'block':'none'}}>
      <iframe ref={iframe} id="newframe" src="http://localhost:3000/" width="100%" height="100%" style={{border:'none'}}/>
    </div>
  );
}

}

ISSUE : second iframe에서 외부 앱 호출 시 실행 안되는 오류

기존 코드

 window.location.href = '외부 앱 호출 링크'

수정 코드

 window.parent.location.href = '외부 앱 호출 링크'
728x90
Comments