Communication APIs

How do we leverage the Internet to interconnect multiple applications?

Cross Document Messaging


            // http://a.com
            var win = window.open("http://b.com");
            win.postMessage("hello world");

            // http://b.com
            window.onmessage = function (e) {
              if (e.origin !== "a.com") {
                return;
              }
              console.log("received message: ", event.data);
            };
          

Network Requests

A browser makes requests for HTML, CSS, JS, and image files via HTTP.

requests

Life of a browser request

request

HTTP vs DNS

http http

HTTP Request


            GET /intdex.html HTTP/1.1
            HOST: www.example.com
          

HTTP Response


            HTTP/1.1 200 OK
            Content-Type: text/html; charset=utf-8
            Content-Length: 11

            Hello World
          

How do we create a request after the page has loaded?

JavaScript

AJAX

Asynchronous JavaScript and XML

Not so much XML anymore.

Used for background HTTP requests after the page has loaded.

AJAX


            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/cats.jpg');
            xhr.onload = function () {
              console.log(xhr.response);
            };
            xhr.send();
          
More info on AJAX methods

HTTP is response/response based.

What if the server has an update for the client?

Poll too much; waste network requests.

Poll not enough; extra latency.

WebSockets

http websockets

WebSockets allow for bidirectional full duplex communication.


            var ws = new WebSocket("ws://a.com");

            ws.onopen = function () { console.log("connected"); };
            ws.onerror = function (e) { console.error(e); };
            ws.onclose = function () { console.log("connection lost"); };

            ws.onmessage = function (e) {
              console.log("received message:", e.data);
            };