# Window.postMessage()
postMessage() 메서드는 Window 객체 사이에서 안전하게 cross-orgin 통신을 할 수 있게 한다.
대표적인 사용 예로 새창으로 띄워진 팝업창, 페이지 안에 포함된 iframe 간에 통신에 사용 할 수 있다.
또 데이터를 보내는 HTTP 요청을 생성하지 않으며, DOM 기반 통신에 사용된다.
* 문법
targetWindow.postMessage(message, targetOrigin, [transfer]);
/*
Window.opener (새 창을 만든 window를 참조할 때),
HTMLIFrameElement.contentWindow (en-US) (부모 window에서 임베디드된 <iframe> (en-US)을 참조할 때),
Window.parent (en-US) (임베디드된 <iframe> (en-US)에서 부모 window를 참조할 때),
Window.frames (en-US) + an index value (named or numeric).
*/
1) message : 다른 window에 보내질 데이터
* 보낼 수 있는 데이터 타입
Array
ArrayBuffer
Boolean
DataView
Date
Error types (but see Error types below).
Map
Number
Object objects: but only plain objects (e.g. from object literals).
Primitive types, except symbol.
RegExp: but note that lastIndex is not preserved.
Set
String
TypedArray
2) targetOrigin
targetWindow의 origin을 지정합니다. 이는 전송되는 이벤트에서 사용되며,
문자열 "*"(별도로 지정하지 않음을 나타냄) 혹은 URI이어야 합니다.
3) transfer (Optional)
일련의 transfer 객체 (en-US). 메세지와 함께 전송됩니다. 이 객체들의 소유권은 수신 측에게 전달되며, 더 이상 송신 측에서 사용할 수 없습니다.
👀 참조 :
https://developer.mozilla.org/ko/docs/Web/API/Window/postMessage
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
# 보내는 쪽 (새창일경우 - 자식에서 부모에게)
window.opener.postMessage({
message: "메시지이름",
url: "보낼url"
},'*');
# 받는쪽
window.addEventListener("message", function(e){
if (typeof e.data == 'object' && e.data.message == '메시지이름') {
window.location.replace(e.data.url ? e.data.url : 'url이 없을경우 보낼 주소');
}
})
- 포스트 메시지를 받았을 때 페이지 이동시키기
# 새창팝업 가운대로 띄우기
function openPopup(site) {
let url = `아무주소`;
var xPos = (document.body.clientWidth / 2) - 250; // width값/2
xPos += window.screenLeft; //듀얼 모니터
var yPos = (screen.availHeight / 2) - 300; // height/2
window.open(url, '팝업이름',"width=500,height=600, left="+xPos+", top="+yPos+", toolbars=no, resizable=no, scrollbars=no");
}
++++ 플러스
php에서 get 요청을 하면 쿼리 스트링으로 넘어온다.
'error & basic' 카테고리의 다른 글
react) 컴포넌트(feat.typescript) #202402 (0) | 2024.02.15 |
---|---|
js) 정규식 & js #2312 (0) | 2023.12.20 |
js) Callback & js #2311 (0) | 2023.11.15 |
js) focus & Vue #2311 (0) | 2023.11.10 |
js) jquery event & php & js #2311 (0) | 2023.11.09 |