React/Next window.open popup 데이터 주고 받기

백경·2022년 6월 17일
0

React 나 Next.js 에서 작업을 할때
popup 을 사용해야 해야하는 경우
데이터를 주고 받는 방법

popup.tsx

const PopupPage: NextPage = () => {
  useEffect(() => {
    const url = location.href;

    const ce = new CustomEvent<string>('popup_data', { detail: url })
    window.opener.dispatchEvent(ce)

    window.close()
  }, [])
  return (<></>)
};
export default PopupPage;

opener.tsx

const Opener: NextPage = () => {
  const onClickPopup = () => {
    const url = `/popup`
    const popup = window.open(
      url,
      '_blank',
      "toolbar=no, location=no, statusbar=no, menubar=no, scrollbars=1, resizable=0, width=450, height=600, top=30, left=30"
    )
   
    addEventListener('popup_data', (ce: CustomEvent) => {
      console.log(`[${ce.type}] ${ce.detail}`)
    })
  }
  
  return (<>
    <div onClick={onClickPopup} >
      Popup
    </div>
  </>
  )
}
export default Opener

Event 로 데이터를 주고 받는다
addEventLisener 를 popup 에 걸지 않고 opener 에 걸어야 한다
popup에 걸어봤는데 동작하지 않는다

profile
Let me introduce myself as an FE developer.

0개의 댓글