카테고리 없음

창종료 또는 새로고침 이벤트 : ajax 결과 전송, 부모창 결과 전송

have a nice day :D 2023. 4. 7. 15:49
반응형

강제 창을 닫거나 새로고침 시, 

'beforeunload' 통해 처리 가능 

크롬에서는 문구는 설정할 수 없으며, '취소', '나가기' 버튼 제어 안됨.

window.addEventListener('beforeunload', (event) => {
    if(isBeforeunload) {
        event.preventDefault();
        event.returnValue = '';
    }
}

 

Sample) 본창과 팝업창이 있고, 팝업창이 강제로 닫혔을 때 본창에서 경고 알림 처리

그래서 [닫기] 이벤트 발생 시, (새로고침 포함)
창을 닫아 버리고, 본 창을 통해 경고 알림 처리


팝업창

let isForceClose = true; // 강제 닫기 체크 여부


// 창종료 또는 새로고침 이벤트
window.addEventListener('beforeunload', (event) => {
    if(isForceClose) {
    	// ajax 결과 전송
        const data = $('form').serializeObjectJson();
        $.ajax({
            type: "post",
            url: '/isForceClose=true',
            data: data
        });


		// 부모창으로 결과 전송
        opener.parent.isForceClose(true);
    }
});

// 저장
function save() {
	isForceClose = false; // form submit 시에는 창종료 이벤트 실행 하지 않음
	$('form').submit();   // 정상 submit
}


본창

function isForceClose(val) {
	alert('팝업 창이 정상적이지 않게 닫혔습니다.');
}

 

반응형