Showing posts with label postMessage. Show all posts
Showing posts with label postMessage. Show all posts

Tuesday, February 7, 2017

Web Communication/Message

MessageEvent: This interface is for message events used in WebSocket, WebRTC RTCDataChannel, server-sent events, cross-document messaging, channel messaging, and broadcast channels.

1. EventSource: This interface is used to receive server-sent events. It connects to a server over HTTP and receives events in text/event-stream format without closing the connection.

2. WebSocket: This interface is used to enable Web applications to maintain bidirectional communications with server-side processes

3. window.postMessage(message, targetOrigin, transfer): This method is used to post message to the given window.
  • Message can be structured objects, e.g. nested objects and arrays, can contain JavaScript values (strings, numbers, Date objects, etc), and can contain certain data objects such as File Blob, FileList, and ArrayBuffer objects.
  • If the origin of the target window doesn't match the given origin, the message is discarded, to avoid information leakage. To send the message to the target regardless of origin, set the target origin to "*". To restrict the message to same-origin targets only, without needing to explicitly state the origin, set the target origin to "/".
  • Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side.
4. MessageChannel: The interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. This will enable independent pieces of code (e.g. running in different browsing contexts) to communicate directly.
  • MessagePort: MessagePort objects are transferable objects, Each channel has two message ports. Data sent through one port is received by the other port, and vice versa.
5. BroadcastChannel: This interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin.

Wednesday, September 12, 2012

postMessage Sample Codes

Cross-document messaging has 2 parts: sender and receivers. Sender can be parent window or child window,  and reciever can be child window and parent window. (sibling windows should also work, for browser tab or windows, need further research.) Here we only talk about the main window includes one iframe case for cross-document (cross-domain) messaging.

Sender (main window):
    var win = document.getElementById("iframe").contentWindow;
    win.postMessage(
            'the-sample-message',
            "http://www.target-origin.com"
    );


Sender (iframe window):
    parent.postMessage(msg, 'http://www.target-origin');

Receiver (onmessage event):
    window.onmessage = function(e){
        if ( e.origin !== "http://www.origin.com" ) {
            return;
        }
        // parse and validate e.data

        // processing e.data
    };

Receiver (customized event handler):
     var handleMessage = function(e) {
         if ( e.origin !== "http://www.origin.com" ) {
            return;
         }     

        // parse and validate e.data
        // processing e.data
    };

    if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage);
    }


References
http://www.w3.org/TR/webmessaging/#web-messaging
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
http://html5demos.com/postmessage2

addEvent utility function (from html5demos.com, good for reference)
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();