๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
JavaScript

[Javascript] postMessage, addEventListener(, attachEvent)

by cheezzz 2021. 12. 28.
๋ฐ˜์‘ํ˜•

postMessage, addEventListener(, attachEvent)๋ฅผ ์ด์šฉํ•œ iframe ๋ถ€๋ชจ์™€ ์ž์‹๊ฐ„์˜ ๋ฉ”์‹œ์ง€ ํ†ต์‹  ๋ฐฉ๋ฒ•

 

- iframe ๋ฉ”์‹œ์ง€ ํ†ต์‹  ์ˆœ์„œ
1. ์–‘์ชฝ ๋ถ€๋ชจ, ์ž์‹ ์œˆ๋„์šฐ์— addEventListener๋ฅผ ์ด์šฉํ•ด message ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ๋“ฑ๋ก
[๋ถ€๋ชจ → ์ž์‹]
2. ๋ถ€๋ชจ ์œˆ๋„์šฐ์—์„œ ์ž์‹ ์œˆ๋„์šฐ iframe์— window.postMessage ์ด์šฉํ•ด ๋ฉ”์‹œ์ง€ ์ „๋‹ฌ
3. ๋ถ€๋ชจ ์œˆ๋„์šฐ๋กœ๋ถ€ํ„ฐ ๋ฉ”์‹œ์ง€๋ฅผ ์ˆ˜์‹ ๋ฐ›๊ณ  ๋“ฑ๋ก๋œ ์ž์‹ ์œˆ๋„์šฐ์˜ addEventListener์˜ message ์ด๋ฒคํŠธ ๋ฐœ์ƒ์‹œํ‚ค๊ณ  ํ•จ์ˆ˜ ํ˜ธ์ถœ
[์ž์‹ → ๋ถ€๋ชจ]
4. ์ž์‹ ์œˆ๋„์šฐ iframe์—์„œ ๋ถ€๋ชจ ์œˆ๋„์šฐ์— window.parent.postMessage ์ด์šฉํ•ด ๋ฉ”์‹œ์ง€ ์ „๋‹ฌ
5. ์ž์‹ ์œˆ๋„์šฐ๋กœ๋ถ€ํ„ฐ ๋ฉ”์‹œ์ง€๋ฅผ ์ˆ˜์‹ ๋ฐ›๊ณ  ๋“ฑ๋ก๋œ ๋ถ€๋ชจ ์œˆ๋„์šฐ์˜ addEventListener์˜ message ์ด๋ฒคํŠธ ๋ฐœ์ƒ์‹œํ‚ค๊ณ  ํ•จ์ˆ˜ ํ˜ธ์ถœ

 

- ๋ฉ”์‹œ์ง€ ์ˆ˜์‹ 

if(window.addEventListener){
	window.addEventListener("message", function, false);
}else if(window.attachEvent){
	window.attachEvent("onmessage", function );
}
  • addEventListener: ์ด๋ฒคํŠธ ๋ฐœ์ƒ์‹œ ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ
  • attachEvent: IE 8 ์ดํ•˜, ์˜คํŽ˜๋ผ์—์„œ addEventListener ๋Œ€์‹  ์‹คํ–‰
  • function: message ์ด๋ฒคํŠธ ๋ฐœ์ƒ์‹œ ํ˜ธ์ถœ๋˜๋Š” ํ•จ์ˆ˜๋ช…

 

- ๋ฉ”์‹œ์ง€ ์†ก์‹ 

// ๋ถ€๋ชจ => ์ž์‹(iframe)
window.postMessage(message, targetOrigin);

// ์ž์‹(iframe) => ๋ถ€๋ชจ
window.parent.postMessage(message, targetOrigin);
  • message: key, value ํ˜•์‹์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ์ „๋‹ฌํ•  ๋ฉ”์‹œ์ง€
  • targetOrigin: ๋ฉ”์‹œ์ง€๋ฅผ ์ˆ˜์‹ ๋ฐ›๋Š” ๋„๋ฉ”์ธ (or ๋ฌธ์ž์—ด "*")

 

 

- ์ฐธ๊ณ ๋ฌธ์„œ
https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener

 

EventTarget.addEventListener() - Web API | MDN

EventTarget์˜ addEventListener() ๋ฉ”์„œ๋“œ๋Š” ์ง€์ •ํ•œ ์ด๋ฒคํŠธ๊ฐ€ ๋Œ€์ƒ์— ์ „๋‹ฌ๋  ๋•Œ๋งˆ๋‹ค ํ˜ธ์ถœํ•  ํ•จ์ˆ˜๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/API/Window/postMessage

 

Window.postMessage() - Web API | MDN

window.postMessage() ๋ฉ”์†Œ๋“œ๋Š” Window ์˜ค๋ธŒ์ ํŠธ ์‚ฌ์ด์—์„œ ์•ˆ์ „ํ•˜๊ฒŒ cross-origin ํ†ต์‹ ์„ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ์‹œ๋กœ, ํŽ˜์ด์ง€์™€ ์ƒ์„ฑ๋œ ํŒ์—… ๊ฐ„์˜ ํ†ต์‹ ์ด๋‚˜, ํŽ˜์ด์ง€์™€ ํŽ˜์ด์ง€ ์•ˆ์˜ iframe ๊ฐ„์˜ ํ†ต์‹ ์— ์‚ฌ์šฉํ• 

developer.mozilla.org

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€