FrankKai / FrankKai.github.io

FE blog
https://frankkai.github.io/
363 stars 39 forks source link

那些闻所未闻的API #87

Closed FrankKai closed 3 years ago

FrankKai commented 6 years ago
FrankKai commented 6 years ago

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.

总结:

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