aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/api/channel_messaging_api/using_channel_messaging/index.html
blob: c6d670b2ef9b4b5a57a6186d5f2557862caa5316 (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
---
title: Using channel messaging
slug: Web/API/Channel_Messaging_API/Using_channel_messaging
translation_of: Web/API/Channel_Messaging_API/Using_channel_messaging
---
<p>{{DefaultAPISidebar("Channel Messaging API")}}</p>

<p><a href="/en-US/docs/Web/API/Channel_Messaging_API">Channel Messaging API</a> 는 두 개의 독립적인 스크립트(예를 들면, 두 개의 IFrame, 또는 메인 다큐먼트와 IFrame, 또는 {{domxref("SharedWorker")}}에 의한 두 개의 다큐먼트)를 각 포트를 가진 양방향 채널(또는 파이프)을 통해 서로 직접 통신할 수 있도록 해줍니다. 이 문서에서 이 기술을 사용하는 기본내용에 대해 살펴봅시다.</p>

<p>{{AvailableInWorkers}}</p>

<h2 id="Use_cases">Use cases</h2>

<p>Channel messaging is mainly useful in cases where you've got a social site that embeds capabilities from other sites into its main interface via IFrames, such as games, address book, or an audio player with personalized music choices. When these act as standalone units, things are ok, but the difficulty comes when you want interaction between the main site and the IFrames, or the different IFrames. For example, what if you wanted to add a contact to the address book from the main site, add high scores from your game into  your main profile, or add new background music choices from the audio player onto the game? Such things are not so easy using conventional web technology, because of the security models the web uses. You have to think about whether the origins trust one another, and how the messages are passed.</p>

<p>Message channels on the other hand can provide a secure channel that a single data item can be sent down, from one browsing context to another, after which the channel is closed. The sending context asks the receiving context for the capability to send a single message. At the receiving end, this message is actioned as appropriate (for example as "add a contact", or "share high scores".)</p>

<div class="note">
<p><strong>Note</strong>: For more information and ideas, the <a href="https://html.spec.whatwg.org/multipage/comms.html#ports-as-the-basis-of-an-object-capability-model-on-the-web">Ports as the basis of an object-capability model on the Web</a> section of the spec is a useful read.</p>
</div>

<h2 id="Simple_examples">Simple examples</h2>

<p>To get your started, we have published a couple of demos on Github. First up, check out our <a href="https://github.com/mdn/dom-examples/tree/master/channel-messaging-basic">channel messaging basic demo</a> (<a href="https://mdn.github.io/dom-examples/channel-messaging-basic/">run it live too</a>), which shows a really simple single message transfer between a page and an embedded {{htmlelement("iframe")}}. The embedded IFrame then sends a confirmation message back. Second, have a look at our <a href="https://github.com/mdn/dom-examples/tree/master/channel-messaging-multimessage">multimessaging demo</a> (<a href="https://mdn.github.io/dom-examples/channel-messaging-multimessage/">run this live</a>), which shows a slightly more complex setup that can send multiple messages between main page and IFrame.</p>

<p>We'll be focusing on the latter example in this article. It looks like so:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/10075/channel-messaging-demo.png" style="display: block; height: 744px; margin: 0px auto; width: 690px;"></p>

<h2 id="Creating_the_channel">Creating the channel</h2>

<p>In the main page of the demo, we have a paragraph and a simple form with a text input for entering messages to be sent to an {{htmlelement("iframe")}}.</p>

<pre class="brush: js">var para = document.querySelector('p');
var textInput = document.querySelector('.message-box');
var button = document.querySelector('button');

var ifr = document.querySelector('iframe');
var otherWindow = ifr.contentWindow;

ifr.addEventListener("load", iframeLoaded, false);

function iframeLoaded() {
  button.onclick = function(e) {
    e.preventDefault();

    var channel = new MessageChannel();
    otherWindow.postMessage(textInput.value, '*', [channel.port2]);

    channel.port1.onmessage = handleMessage;
    function handleMessage(e) {
      para.innerHTML = e.data;
      textInput.value = '';
    }
  }
}</pre>

<p>When the IFrame has loaded, we run an <code>iframeLoaded()</code> function containing an <code>onclick</code> handler for our button — when the button is clicked, we prevent the form submitting as normal, create a new message channel with the {{domxref("MessageChannel()","MessageChannel.MessageChannel")}} constructor, then send the value entered in our text input to the IFrame via the {{domxref("MessageChannel")}}. Let's explore how the <code>window.postMessage</code> line works in a bit more detail.</p>

<p>For a start, here we are calling the {{domxref("window.postMessage")}} method — we are posting a message to the IFrame's window context. {{domxref("window.postMessage")}} has three arguments, unlike {{domxref("MessagePort.postMessage")}}, which only has two. The three arguments are:</p>

<ol>
 <li>The message being sent, in this case <code>textInput.value</code>.</li>
 <li>The origin the message is to be sent to. * means "any origin".</li>
 <li>An object, the ownership of which is transferred to the receiving browsing context. In this case, we are transferring {{domxref("MessageChannel.port2")}} to the IFrame, so it can be used to receive the message from the main page.</li>
</ol>

<p>At the bottom of the <code>iframeLoaded()</code> function there is a {{domxref("MessagePort.onmessage")}} handler, but we'll get to that later.</p>

<h2 id="Receiving_the_port_and_message_in_the_IFrame">Receiving the port and message in the IFrame</h2>

<p>Over in the IFrame, we have the following JavaScript:</p>

<pre class="brush: js">var list = document.querySelector('ul');

onmessage = function(e) {
  var listItem = document.createElement('li');
  listItem.textContent = e.data;
  list.appendChild(listItem);
  e.ports[0].postMessage('Message received by IFrame: "' + e.data + '"');
}</pre>

<p>The entirety of the code is wrapped in a {{domxref("window.onmessage")}} handler, which runs when the message is received from the main page (via its <code>postMessage()</code>.) First we create a list item and insert it in the unordered list, setting the {{domxref("textContent","Node.textContent")}} of the list item equal to the event's <code>data</code> attribute (this contains the actual message).</p>

<p>Next, we post a confirmation message back to the main page via the message channel, using <code>e.ports[0].postMessage()</code>. How does this work? Earlier we transferred <code>port2</code> over to the IFrame — this is accessible in the event's <code>ports</code> attribute (array position <code>[0]</code>). We call {{domxref("MessagePort.postMessage")}} on this port — since <code>port2</code> is being controlled by the IFrame, and it is joined to port1 by the message channel, the specified message will be sent back to the main page.</p>

<h2 id="Receiving_the_confirmation_in_the_main_page">Receiving the confirmation in the main page</h2>

<p>Returning to the main page, let's now look at the onmessage handler at the bottom of the <code>iframeLoaded()</code> function:</p>

<pre class="brush: js">channel.port1.onmessage = handleMessage;
function handleMessage(e) {
  para.innerHTML = e.data;
  textInput.value = '';
}</pre>

<p>Here we are setting <code>port1</code>'s {{domxref("MessagePort.onmessage")}} handler equal to the <code>handleMessage()</code> function — when a message is received back from the IFrame confirming that the original message was received successfully, this simply outputs the confirmation to a paragraph and empties the text input ready for the next message to be sent.</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('HTML WHATWG', 'web-messaging.html#channel-messaging', 'Channel messaging')}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<h3 id="MessageChannel"><code>MessageChannel</code></h3>

<p>{{Compat("api.MessageChannel", 0)}}</p>

<h3 id="MessagePort"><code>MessagePort</code></h3>

<p>{{Compat("api.MessagePort", 0)}}</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/Channel_Messaging_API">Channel Messaging API</a></li>
 <li><a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers API</a></li>
 <li><a href="/en-US/docs/Web/API/Broadcast_Channel_API">Broadcast Channel API</a></li>
</ul>