1. 문제발생
리엑트로 만들어진 페이지에서 윈도우 팝업을 오픈하고, 해당 팝업 내부에서 이벤트를 통해 부모창에서 추가 팝업을 열고자 했는데 팝업이 차단되어있어 팝업이 open되지 않는 상황 >
사용자에게 해당 상황에 팝업이 차단되어있다는 사실을 고지하기 위해 부모창에서 alert을 띄웠지만 열려있는 팝업때문에 사용자에게 노출이 되지 않는 문제가 발생하였다.
2. 해결방법
첫번째 팝업을 ref로 관리하여 postMessage를 통해 팝업에 직접적으로 alert출력
3. 코드
// 첫번째팝업 ref에 할당
popElement.current = window.open('', '_blank', `width=${width},height=${height},top=${top},left=${left}`);
// 팝업 코드 할당
let element = <사용자 작성 페이지 컴포넌트 />
const htmlString = ReactDOMServer.renderToString(element);
let script = `
<script>
...
//클릭이벤트 postMessage (두번째팝업 오픈이벤트)
const info = document.querySelectorAll('.clickBtn');
info.forEach(el => {
el.addEventListener('click', function() {
const id = el.getAttribute('id');
window.opener.postMessage({ type: 'selectedItem', id }, '*');
});
});
// alert postMessage (두번째팝업 null일경우 alert 이벤트)
window.addEventListener('message', function(event) {
if (event.origin === window.origin) {
alert(event.data);
}
});
</script>
`;
let printHtml = htmlString + script;
popElement.current.document.writeln(printHtml);
// 두번째팝업 오픈이벤트 분기
useEffect(() => {
const handleMessage = (event) => {
if (event.data.type === 'selectedItem') {
두번째팝업func(event.data.id);
}
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
// 두번째팝업 오픈이벤트
const printWindow = window.open('', '_blank', `width=${width},height=${height},top=${top},left=${left}`);
// 두번째팝업 null일경우 예외처리
if (!printWindow || printWindow.closed || typeof printWindow.closed === 'undefined') {
if (popElement.current) {
popElement.current.postMessage("Pop-ups are blocked. Please disable your pop-up blocker and try again.");
}
return;
}
'react' 카테고리의 다른 글
React - 특정 데이터의 Null 여부 확인하기 (0) | 2024.08.02 |
---|---|
React - grid 데이터 특정값의 합/count 구하기(reduce, callback) (0) | 2024.08.02 |
SpringBoot - React CORS Error 해결 (0) | 2023.05.24 |
Breadcrumb 만들기 (0) | 2023.05.16 |
페이지 인쇄 구현 (0) | 2023.05.16 |