6. Cross-Document Messaging
• Simple API to send and receive in-window
messages
• Send messages using the postMessage function
• Wire handlers to the message event
6
window.postMessage(message, domain);
window.addEventListener("message", function () {
// do something
}, false);
9. Cross-Origin Resource Sharing
(CORS)
• Browsers prevent cross-domain JavaScript requests
• CORS enables cross-domain requests as long as:
o Response includes Access-Control-Allow-Origin header
o XMLHttpRequest supports CORS
• XDomainRequest in IE8 and IE9
10. CORS – Client Side
var xhr = new XMLHttpRequest();
xhr.open(“get”, url, true);
xhr.onload = function () {
// instead of using onreadystatechange
}
xhr.send();
11. CORS – Client Side API
• Functions:
o abort() – stops a request that is already in progress
o send() – sends a request to the server
• Event handlers:
o onerror – handles request errors
o onload – handles request success
12. CORS – Access Control Flow
• Client sends ‘Access-Control’ headers during
request preflight
o Using the OPTIONS HTTP request
• Server checks whether the requested resource is
allowed
• Client checks the preflight response and decides
whether to allow the request
13. CORS – Server Side
• Use Access-Control headers to allow
o Origin – Specific request URI
o Method – request method (GET, POST and etc.)
o Headers – optional custom headers
o Credentials – request credentials
16. Server-Sent Events
• Enables servers to push data over HTTP using push
protocols
• Use the EventSource JavaScript API
var source = new EventSource(url);
source.onmessage = function (e) {
console.log(e.data);
}
17. Server-Sent Events - Server
• Strict server protocol:
• Response content type should be text/event-stream
• Keeps the connection open
data: This is a message.
event: add
data: 73857293
22. Web Sockets
• Bidirectional communications channels, over a
single TCP socket
• Don’t allow raw access to the underlying network
• Can replace old techniques such as:
o Forever frames
o Long-polling/comet
23. Web Sockets – Client Request
• The client sends a WebSocket handshake request
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
24. Web Sockets – Server Response
• The server responses with a WebSocket handshake
response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
25. Web Sockets – API
• Create a WebSocket object using a URL
• Use the WebSocket object’s built-in events:
o onopen – fired when a web socket has opened
o onmessage – fired when a message has been received
o onclose – fired when a web socket has been closed