html5/javascript communication apis - dpc 2014

18
www.arrabiata.co.uk HTML5/JavaScript Communication APIs Dutch PHP Conference, 27.06.2014 Christian Wenz [email protected]

Upload: christian-wenz

Post on 17-Dec-2014

255 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: HTML5/JavaScript Communication APIs - DPC 2014

www.arrabiata.co.uk

HTML5/JavaScript Communication APIs

Dutch PHP Conference, 27.06.2014

Christian Wenz

[email protected]

Page 2: HTML5/JavaScript Communication APIs - DPC 2014

Arrabiata Solutions

::As a specialist for digital solutions we offer our clients all services from

conception to realization, support and optimization. Our focus is international

with offices in Munich and London. Arrabiata Solutions was founded in 2006

and has more than 30 employees with a combined experience of over 100

successful projects. ::

Arrabiata is a full-service digital agency.

Page 3: HTML5/JavaScript Communication APIs - DPC 2014

AGENDA

STATUS QUO

WORKING AROND SOP

MESSAGING API

SSE & WEB SOCKETS

CONCLUSION

Page 4: HTML5/JavaScript Communication APIs - DPC 2014

Status Quo

• GET requests via anything with an src attribute

– No restrictions

– Only possible to provide URL

• Any (browser-supported) HTTP verb via XMLHttpRequest

– Can set headers and HTTP body

– Restricted by SOP (same-origin policy)• Protocol, domain, port

• Still using HTTP

Page 5: HTML5/JavaScript Communication APIs - DPC 2014

Working around SOP: JSONP

• JSON with padding

• Ajax call:– <script src="http://domain/file.ashx?jsonp=func">

</script>

• Return value:– func([1, 2, 3]);

• „Padding“ is „func“

• Works in virtually any browser

• Still is kinda hackish

Page 6: HTML5/JavaScript Communication APIs - DPC 2014

CORS

• Cross-Origin Resource Sharing

• Works around the Same Origin Policy

• Restrictions must be met, though– Specific Content-type header

– Origin header

– Server uses Access-Control-Allow-Origin header(value must be * or Origin header for the browserto proceed)

• Advanced approach: preflighted requests (e.g. for POST requests to avoid CSRF)

Page 7: HTML5/JavaScript Communication APIs - DPC 2014

Messaging API

• Simple cross-domain mechanism to send/receive data

• Works everywhere except IE7-, and limited in IE8+

• Sending:– Access other window (e.g. contentWindow

property of an iframe)– Use postMessage() method to send data (1st

argument)– For security reasons, use origin of target site as

2nd argument

Page 8: HTML5/JavaScript Communication APIs - DPC 2014

Messaging API (2)

• Receiving:

– Wait for window‘s message event.

– Event arguments contain the data sent (dataproperty) and the origin of the sender (originproperty)

– Use postMessage() to send data back to theorigin

– Sender may use the message event as well to process the data from the receiver.

Page 9: HTML5/JavaScript Communication APIs - DPC 2014

Server-Sent Events

• JavaScript API for long polling requests

• Server continously sends data, the client just receives and processes them

• Step 1: subscribe to source

– var es = new EventSource("polling.ext");

• Step 2: listen to message event

– es.onmessage = function(ev) {console.log(ev.data);

};

• Works almost everywhere except IE

Page 10: HTML5/JavaScript Communication APIs - DPC 2014

Stream Format

• Content-type: text/event-stream

• Fields: id, data, event, retry (all optional!)

• Format: <field>: <value>

• Blank lines between fields

• id: 123data: abc

id: 456event: def

Page 11: HTML5/JavaScript Communication APIs - DPC 2014

Reconnecting to the Server

• Browser reconnects the connection everyfew seconds (unless changed by retrystream value)

• Browser sends Last-Event-ID HTTP header ifserver sent ID before

• Allows server to only send new events

Page 12: HTML5/JavaScript Communication APIs - DPC 2014

Web Sockets

• Full duplex communication

• Circumvents a few of the disadvantages ofHTTP (metadata sent with each request, re-establishment of the connection, etc.)

• Works in all recent browsers except IE9-

Page 13: HTML5/JavaScript Communication APIs - DPC 2014

HTTP Handshake

• Request:GET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13Origin: http://example.com

• Response:HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=Sec-WebSocket-Protocol: chat

Page 14: HTML5/JavaScript Communication APIs - DPC 2014

API for Web Sockets

• Server: depends on the technology used; node.js is theposter child of the month

• Client: – var w = new WebSocket("ws://server:1234");

– w.onopen = function(ev) {w.send("Hi!");

}

w.onmessage = function(ev) {console.log(ev.data);

}

Page 15: HTML5/JavaScript Communication APIs - DPC 2014

Websocket Server with node.js

var server = require('http');var webSocketServer = require("websocket").server;

server.listen(1234);

var wsServer = new webSocketServer({httpServer: server

});

wsServer.on('request', function(request) { …

});

Page 16: HTML5/JavaScript Communication APIs - DPC 2014

Socket.IO

• There are countless protocol versions for Web Sockets

• Better use an abstraction layer that also provides polyfillsfor browsers that use an older API version, e.g. Socket.IO (http://socket.io/).

• Server:– var io = require("socket.io").listen(1234);

• Client:– var ws = io.connect("http://127.0.0.1:1234");

Page 17: HTML5/JavaScript Communication APIs - DPC 2014

Decision Chart

Technique X-Domain Return data Backchannel Long running High Performance

src

XHR

JSONP

CORS

Messaging

Workers

Server-SentEvents

Web Sockets

Page 18: HTML5/JavaScript Communication APIs - DPC 2014

Thank You!

[email protected]

• http://www.arrabiata.co.uk/

• @chwenz

• Rate this session: http://joind.in/talk/view/10857