• Save
Message in a Bottle
Upcoming SlideShare
Loading in...5
×
 

Message in a Bottle

on

  • 2,361 views

Review of server-client and client-client messaging using HTML5 technologies

Review of server-client and client-client messaging using HTML5 technologies

Statistics

Views

Total Views
2,361
Views on SlideShare
1,973
Embed Views
388

Actions

Likes
1
Downloads
0
Comments
0

4 Embeds 388

http://www.w3c.org.il 323
http://webmaster.org.il 43
http://frontend.co.il 21
https://www.google.co.il 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Message in a Bottle Message in a Bottle Presentation Transcript

  • Message in a bottleClient-Client and Client-Server communication with HTML5Zohar Arad. October 2011
  • Introduction Background - Front-end and Web developer since 2004 Metacafe, Rounds, Newsgeek, 106fm, Quicklizard, Crossrider, Superfly and others Client-Side and UI architecting Client-Server integration HTML & CSS, JS, Ruby, Node
  • We’re going to talk about...Passing message in the browser • To the user (Desktop notifications) • To the browser (postMessage) • To the server (CORS) • From the server (Server-Side Events) View slide
  • Desktop NotificationsIntegrating the browser with the desktop View slide
  • Desktop Notifications Lets us display a notification message to the user Displays the message in the context of the browser application, rather than the active window Non-blocking (unlike alert / confirm) Supports HTML content
  • Desktop Notifications Still not part of HTML5 Only supported by Chrome Very useful for browser-based apps Requires explicit user permission (same as Geo API)
  • function RequestPermission(callback){ window.webkitNotifications.requestPermission(callback);} function showNotification(){ if (window.webkitNotifications.checkPermission() > 0) { RequestPermission(showNotification); } else { window.webkitNotifications.createNotification( "http://www.mysite/images/some_image.png", "My Title", "Hello stranger" ).show(); }}
  • Desktop Notifications - API checkPermission - Check notification permissions requestPermission(callback) - Ask for notifications permissions createNotification(image, title, text) - create text notification createHTMLNotification(html_url) - create HTML notification
  • Desktop Notifications - API show - Show a created notification cancel - Hide a created notification
  • Desktop Notifications - Flow Check notification permissions (domain-specific) Ask for notification permissions if needed Create a notification object Display the notification Hide when appropriate
  • Cross-Window MessagingLook Ma, no hacks
  • Posting messages between windowsWe have two windows under our controlThey don’t necessarily reside under the same domainHow can we pass messages from one window to theother?
  • We used to hack it away Change location.hash Change document.domain (if subdomain is different) Use opener reference for popups Throw something really heavy, really hard
  • No more evil hackspostMessage brings balance to the force
  • Message passingEventedSender / Receiver modelReceiver is responsible for enforcing security
  • postMessage - Receiverwindow.addEventListener(“message”,onMessage,false);function onMessage(e){ if(e.origin === ‘http://www.mydomain.com’){ console.log(‘Got a message’,e.data); }}
  • postMessage - Sendertop.postMessage(‘Hi from iframe’, ‘http://www.mydomain.com’);
  • postMessage - Sending to iframesvar el = document.getElementById(‘my_iframe’);var win = el.contentWindow;win.postMessage(‘Hi from iframe parent’, ‘http://www.mydomain.com’);
  • postMessage - Sending to popupvar popup = window.open(......);popup.postMessage(‘Hi from iframe parent’, ‘http://www.mydomain.com’);
  • When should you use it? Browser extensions Embedded iframes (if you must use such evil) Flash to Javascript
  • Cross-Origin Resource SharingThe evolution of XHR
  • In the good ol’ days... We had XHR (Thank you Microsoft) We could make requests from the client to the server without page reload We were restricted to the same-origin security policy - No cross-domain requests
  • This led to things like JSONP Flash-driven requests Server-side proxy Using iframes (express your frustration here)
  • Thankfully,these days are (nearly) gone
  • Say Hello to CORS
  • CORS is the new AJAXCross-domain requests are allowedServer is responsible for defining the security policyClient is responsible for enforcing the security policyWorks over standard HTTP
  • CORS - Client Sidevar xhr = new XMLHttpRequest();xhr.open(‘get’, ‘http://www.somesite.com/some_resource/’, true);xhr.onload = function(){ //instead of onreadystatechange};xhr.send(null);
  • Someone has to be different
  • CORS - Client Side (IE)var xhr = new XDomainRequest();xhr.open(‘get’,‘http://www.somesite.com/some_resource/’);xhr.onload = function(){ //instead of onreadystatechange};xhr.send();
  • CORS - Client Side API abort() - Stop request that’s already in progress onerror - Handle request errors onload - Handle request success send() - Send the request responseText - Get response content
  • CORS - Access Control Flow The client sends ‘Access-Control’ headers to the server during request preflight The server checks whether the requested resource is allowed The client checks the preflight response and decides whether to allow the request or not
  • CORS - Server Side Use Access-Control headers to allow Origin - Specific request URI Method - Request method(s) Headers - Optional custom headers Credentials - Request credentials (cookies, SSL, HTTP authentication (not supported in IE)
  • CORS - Server SideAccess-Control-Allow-Origin: http://www.somesite.com/some_resourceAccess-Control-Allow-Methods: POST, GETAccess-Control-Allow-Headers: NCZAccess-Control-Max-Age: 84600Access-Control-Allow-Credentials: true
  • CORS - RecapClient sends a CORS request to the serverServer checks request headers for access controlaccording to URI, method, headers and credentialsServer responds to client with an access control responseClient decides whether to send the request or not
  • CORS - Why should you use it? It works on all modern browser (except IE7 and Opera) It doesn’t require a lot of custom modifications to your code Its the new AJAX (just like the new Spock) You can fall back to JSONP or Flash Using CORS will help promote it Works on Mobile browsers (WebKit)
  • Server-Side EventsMessage in an HTTP bottle
  • Server-Side Events Stream data from the server to the client Works over plain HTTP. No special protocol required Half-duplex - You can give but you cannot receive Not as full-featured as WS but just as useful
  • Server-Side Events - Client var source = new EventSource(‘/path/to/stream’);source.addEventListener(‘open’, function(e) { // Connection was opened.}, false);source.addEventListener(‘error’, function(e) { if (e.eventPhase == EventSource.CLOSED) { // Connection was closed. }}, false);
  • Server-Side Events - Clientsource.addEventListener(‘message’, function(e) { console.log(e.data);}, false);source.addEventListener(‘userlogin’, function(e) { if(e.origin === ‘http://mysite.com’){ // do something with e.data }}, false);
  • Server-Side Events - Server data: Hi Everyonen id: 12345n data: {msg:"Hello HTML5Fest"} retry: 5000n data: rety menn
  • Server-Side Events - Server data: {"msg": "First message"}nn event: userloginn data: {"username": "John123"}nn event: updaten data: {"username": "John123", "emotion": "happy"}nn
  • Server-Side Events - Server Response content-type should be text/event-steam Flush buffer after every chunk Keep the connection open
  • header(‘Content-Type: text/event-stream’);header(‘Cache-Control: no-cache’);function sendMsg($id, $msg) { echo “id: $id” . PHP_EOL; echo “data: $msg” . PHP_EOL; echo PHP_EOL; ob_flush(); flush();}sendMsg(time(), ‘server time: ‘ . date(“h:i:s”, time()));
  • Server-Side Events - Recap Works over plain old HTTP Half-Duplex - Only from server to client Messages are sent in plain text with text/event-stream content-type Supported by Chrome, Safari 5+, FF 6+, Opera 11+
  • When should I use SSE? Whenever full-duplex communication is not required Push data application Sending data to server can be done over plain XHR When implementing as a separate service is not feasible When Web-Sockets are not an option
  • Server-Side Events - Demo Demo - http://html5sse.cloudfoundry.com/ Source - https://github.com/zohararad/html5sse
  • Final Words Questions?
  • Zohar Aradwww.frontendworks.comwww.zohararad.com