Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

那些闻所未闻的API #87

Closed
FrankKai opened this issue Aug 5, 2018 · 1 comment
Closed

那些闻所未闻的API #87

FrankKai opened this issue Aug 5, 2018 · 1 comment

Comments

@FrankKai
Copy link
Owner

FrankKai commented Aug 5, 2018

  • Channel Messaging API
@FrankKai
Copy link
Owner Author

FrankKai commented Aug 6, 2018

Channel Message API

The Channel Messaging API allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a SharedWorker, or two workers) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end.

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.

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".)

image

demo:https://github.com/mdn/dom-examples/tree/master/channel-messaging-multimessage

page1:https://github.com/mdn/dom-examples/blob/master/channel-messaging-multimessage/index.html

<script>
    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]);//发送消息到子IFrame
        channel.port1.onmessage = handleMessage;//接收子IFrame发来的消息
        function handleMessage(e) {
          para.innerHTML = e.data;
          textInput.value = '';
        } 
      }
    }
  </script>

page2:https://github.com/mdn/dom-examples/blob/master/channel-messaging-multimessage/page2.html

var list = document.querySelector('ul');
  onmessage = function(e) {
    var listItem = document.createElement('li');
    listItem.textContent = e.data;
  	list.appendChild(listItem);
  	// e.ports[0] is channel.port2, sent from the main frame
  	e.ports[0].postMessage('Message received by IFrame: "' + e.data + '"');//发送消息到主页面
  }

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

For a start, here we are calling the window.postMessage method — we are posting a message to the IFrame's window context. window.postMessage has three arguments, unlike MessagePort.postMessage, which only has two. The three arguments are:

The message being sent, in this case textInput.value.
The origin the message is to be sent to. * means "any origin".
An object, the ownership of which is transferred to the receiving browsing context. In this case, we are transferring MessageChannel.port2 to the IFrame, so it can be used to receive the message from the main page.
At the bottom of the iframeLoaded() function there is a MessagePort.onmessage handler, but we'll get to that later.

总结:

  • 主Frame通过port2发送信息,通过port1接收信息。
  • 副Frame通过与主Frame建立连接的port2发送消息,接收消息不需指定port。

参考:https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant