별의 공부 블로그 🧑🏻‍💻

Web Messaging

Programming/HTML5 2017. 5. 19. 21:36
728x90
728x170

* Web Messaging이란?

- JavaScript에서는 오리진이 다른 문서 간에 보안상의 이유로 데이터를 주고받거나 오브젝트에 액세스하는 데 제한이 있음.

- Web Messaging은 이러한 제한을 넘어서 안전하게 데이터를 주고받을 수 있는 API임.

- 오리진은 문서의 URL 중 스킴, 도메인, 포트를 합친 것을 말함.

- Web Messaging에는 아래의 두 가지 API가 있음.

1. 크로스 도큐먼트 메시징 : 탭이나 창 단위로 통신을 구현함.

2. 채널 메시징 : 좀 더 작은 단위로 통신을 구현함.

 

* 크로스 도큐먼트 메시징의 이용

- 크로스 도큐먼트 메시징을 이용하려면 송신처의 window 오브젝트의 postMessaging() 메서드를 호출해야 함.

 

var targetWindow = frame.contentWindow;         // 프레임 내의 window를 구함.

targetWindow.postMessage("메시지", "*");

                  송신하고 싶은 데이터   송신처의 오리진(*는 임의의 오리진)

 

[크로스 도큐먼트 메시징의 수신]

 

- 크로스 도큐먼트 메시징으로 보내진 데이터를 취득하려면, window 오브젝트의 message 이벤트를 이용해야 함.

- 받은 데이터는 이벤트 인수인 data 속성으로 꺼낼 수 있음.

- document 요소 등 특정 window에 연결된 오브젝트는 송수신할 수 없음.

 

window.onmessage = function (event) {

// 보내온 데이터

var message = event.data;

// 송신처의 오리진

var origin = event.origin;

// 송신처의 window 오브젝트

var source = event.source;

데이터를 수신했을 때의 처리

}

 

 

[크로스 도큐먼트 메시징의 예]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[http://example.net/index.html]
 
<!DOCTYPE html>
<html lang="kr">
<head>
    <meta charset=utf-8>
    <title>Web Messaging 예제</title>
    <script type="text/javascript">
        function onLoad(event) {
            var frame = document.getElementById("frame");
            var targetWindow = frame.contentWindow;
            targetWindow.postMessage("메시지""http://example.com/");
        }
    </scrpt>
</head>
<body>
    <iframe id="frame" onload="onLoad(event);" src="http://example.com/other.html">
</body>                    // 프레임 읽기가 완료되기를 기다렸다가 데이터의 송수신을 시작함.
</html>
 
[http://example.net/other.html (JavaScript 부분만 발췌)]

 

window.onmessage = function(event) {
    if(event.origin == "http://example.net") {        // 안전을 위해 송신처의 오리진을 체크함.
        var message = event.data;
        /* ㅔ이터 수신 시의 처리 */
    }
}
cs

 

 

* 채널 메시징의 이용

- 채널 메시징에서는 MessageChannel 오브젝트를 하나 단위로 해서 그 port1 속성과 port2 속성에 저장되어 있는 2개의 MessagePort 오브젝트 사이에 데이터를 주고 받음.

- MessagePort 오브젝트(port1, port2)에는 송신용인 'portMessage(message)' 메서드와 수신용인 'message' 이벤트가 있음.

- 짝이 되는 포트 중, 한쪽이 송신 메서드를 호출하면 다른 한쪽에서는 수신 이벤트가 발생하고, 데이터가 보내짐.

 

var channel = new MessageChannel();

channel.port1.start();

channel.port2.start();        // port는 통신 전에 반드시 start()로 초기화해야 함.

// port1의 수신 핸들러 정의

channel.port1.onmessage = function(event) {

var message = event.data;

}

// port2에서 port1로 데이터 송신

channel.port2.postMessage("송신 메시지");

 

 

[다른 window간의 채널 메시징]

 

- 서로 다른 문서 간에 채널 메시징을 수행하려면, 짝이 되는 MessagePort의 한쪽을 크로스 도큐먼트 메시징을 이용해서 상대방의 문서에 보내 전달해야 함.

- 특정 회선으로 맞춘 무전기를 상대에게 우송하는 것과 같은 이미지임.

- 크로스 도큐먼트 메시징을 이용하여 MessagePort를 송신하려면, 송신 메서드의 추가 인수에 송신할 port를 저장한 배열을 지정해야 함.

- 수신 측에서 이 배열은 이벤트 인수의 'ports' 속성으로부터 추출함.

- 예)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html lang="kr">
<head>
<meta charset=utf-8>
<title>Web Messaging 예제</title>
<script type="text/javascript">
    function onLoad(event) {
        var frame = document.getElementById("frame");
        var targetWindow = frame.contentWindow;
 
        var channel = new MessageChannel();
        channel.port1.start();
        channel.port2.start();
 
        // port1의 수신 핸들러 정의
        channel.port1.onmessage = function(event) {
            /* 메시지 수신 시의 처리 */
        }
 
        // port2를 상대방에게 송신
        targetWindow.postMessage("", [channel.port2], "http://example.com/");
                                // 송신할 port를 저장할 배열을 제2인수로 지정함. (Chrome, Safari의 경우, Opera에서는 제3인수가 됨.)
    }
    </script>
</head>
<body>
    <iframe id="frame" onload="onLoad(event);" src="http://example.com/other.html">
</body>
 
</html>
 
[http://example.com/other.html(JavaScript 부분만 발췌)]
 
window.onmessage = function(event) {
    if(event.origin == "http://example.net") {
        var port2 = event.ports[0];     // 보내온 port를 취득함.
        // port2에서 port1로 데이터 송신
        port2.postMessage("송신 메시지");
    }
}
cs

 

[지원 상황]

 

 

IE 

Firefox 

Opera 

Safari 

Chrome 

Web Messaging

 O 

O

O

 

 

내용 출처 : HTML5가 보이는 그림책 (ANK Co., Ltd 저, 성안당)

728x90
그리드형(광고전용)

'Programming > HTML5' 카테고리의 다른 글

[textarea] 영역 크기 조절 방지  (0) 2021.04.19
(X)HTML 요점 정리  (0) 2017.05.20
WebSocket  (0) 2017.05.19
Server-Sent Events  (0) 2017.05.19
ApplicationCache  (0) 2017.05.19
Web Workers  (0) 2017.05.19
File API  (0) 2017.05.19
Indexed Database API  (0) 2017.05.19
⚠️AdBlock이 감지되었습니다. 원할한 페이지 표시를 위해 AdBlock을 꺼주세요.⚠️
starrykss
starrykss
별의 공부 블로그 🧑🏻‍💻


📖 Contents 📖