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, Crossride...
We’re going to talk about...Passing message in the browser • To the user (Desktop notifications) • To the browser (postMes...
Desktop NotificationsIntegrating the browser with the desktop
Desktop Notifications Lets us display a notification message to the user Displays the message in the context of the browse...
Desktop Notifications Still not part of HTML5 Only supported by Chrome Very useful for browser-based apps Requires explici...
function RequestPermission(callback){  window.webkitNotifications.requestPermission(callback);} function showNotification(...
Desktop Notifications - API checkPermission - Check notification permissions requestPermission(callback) - Ask for notific...
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 C...
Cross-Window MessagingLook Ma, no hacks
Posting messages between windowsWe have two windows under our controlThey don’t necessarily reside under the same domainHo...
We used to hack it away Change location.hash Change document.domain (if subdomain is different) Use opener reference for p...
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://w...
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(‘...
postMessage - Sending to popupvar popup = window.open(......);popup.postMessage(‘Hi from iframe parent’,                ‘h...
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...
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 respo...
CORS - Client Sidevar xhr = new XMLHttpRequest();xhr.open(‘get’,         ‘http://www.somesite.com/some_resource/’,        ...
Someone has to be different
CORS - Client Side (IE)var xhr = new XDomainRequest();xhr.open(‘get’,‘http://www.somesite.com/some_resource/’);xhr.onload ...
CORS - Client Side API abort() - Stop request that’s already in progress onerror - Handle request errors onload - Handle r...
CORS - Access Control Flow The client sends ‘Access-Control’ headers to the server during request preflight The server che...
CORS - Server Side Use Access-Control headers to allow  Origin - Specific request URI  Method - Request method(s)  Headers...
CORS - Server SideAccess-Control-Allow-Origin: http://www.somesite.com/some_resourceAccess-Control-Allow-Methods: POST, GE...
CORS - RecapClient sends a CORS request to the serverServer checks request headers for access controlaccording to URI, met...
CORS - Why should you use it? It works on all modern browser (except IE7 and Opera) It doesn’t require a lot of custom mod...
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-dupl...
Server-Side Events - Client  var source = new EventSource(‘/path/to/stream’);source.addEventListener(‘open’, function(e) {...
Server-Side Events - Clientsource.addEventListener(‘message’, function(e) {  console.log(e.data);}, false);source.addEvent...
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: upda...
Server-Side Events - Server Response content-type should be text/event-steam Flush buffer after every chunk Keep the conne...
header(‘Content-Type: text/event-stream’);header(‘Cache-Control: no-cache’);function sendMsg($id, $msg) {    echo “id: $id...
Server-Side Events - Recap Works over plain old HTTP Half-Duplex - Only from server to client Messages are sent in plain t...
When should I use SSE? Whenever full-duplex communication is not required  Push data application  Sending data to server c...
Server-Side Events - Demo Demo - http://html5sse.cloudfoundry.com/ Source - https://github.com/zohararad/html5sse
Final Words Questions?
Zohar Aradwww.frontendworks.comwww.zohararad.com
Upcoming SlideShare
Loading in...5
×

Message in a Bottle

2,469

Published on

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

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,469
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • \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

    1. 1. Message in a bottleClient-Client and Client-Server communication with HTML5Zohar Arad. October 2011
    2. 2. 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
    3. 3. 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)
    4. 4. Desktop NotificationsIntegrating the browser with the desktop
    5. 5. 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
    6. 6. 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)
    7. 7. 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(); }}
    8. 8. 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
    9. 9. Desktop Notifications - API show - Show a created notification cancel - Hide a created notification
    10. 10. Desktop Notifications - Flow Check notification permissions (domain-specific) Ask for notification permissions if needed Create a notification object Display the notification Hide when appropriate
    11. 11. Cross-Window MessagingLook Ma, no hacks
    12. 12. 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?
    13. 13. 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
    14. 14. No more evil hackspostMessage brings balance to the force
    15. 15. Message passingEventedSender / Receiver modelReceiver is responsible for enforcing security
    16. 16. postMessage - Receiverwindow.addEventListener(“message”,onMessage,false);function onMessage(e){ if(e.origin === ‘http://www.mydomain.com’){ console.log(‘Got a message’,e.data); }}
    17. 17. postMessage - Sendertop.postMessage(‘Hi from iframe’, ‘http://www.mydomain.com’);
    18. 18. postMessage - Sending to iframesvar el = document.getElementById(‘my_iframe’);var win = el.contentWindow;win.postMessage(‘Hi from iframe parent’, ‘http://www.mydomain.com’);
    19. 19. postMessage - Sending to popupvar popup = window.open(......);popup.postMessage(‘Hi from iframe parent’, ‘http://www.mydomain.com’);
    20. 20. When should you use it? Browser extensions Embedded iframes (if you must use such evil) Flash to Javascript
    21. 21. Cross-Origin Resource SharingThe evolution of XHR
    22. 22. 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
    23. 23. This led to things like JSONP Flash-driven requests Server-side proxy Using iframes (express your frustration here)
    24. 24. Thankfully,these days are (nearly) gone
    25. 25. Say Hello to CORS
    26. 26. 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
    27. 27. 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);
    28. 28. Someone has to be different
    29. 29. 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();
    30. 30. 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
    31. 31. 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
    32. 32. 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)
    33. 33. 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
    34. 34. 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
    35. 35. 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)
    36. 36. Server-Side EventsMessage in an HTTP bottle
    37. 37. 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
    38. 38. 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);
    39. 39. 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);
    40. 40. Server-Side Events - Server data: Hi Everyonen id: 12345n data: {msg:"Hello HTML5Fest"} retry: 5000n data: rety menn
    41. 41. Server-Side Events - Server data: {"msg": "First message"}nn event: userloginn data: {"username": "John123"}nn event: updaten data: {"username": "John123", "emotion": "happy"}nn
    42. 42. Server-Side Events - Server Response content-type should be text/event-steam Flush buffer after every chunk Keep the connection open
    43. 43. 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()));
    44. 44. 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+
    45. 45. 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
    46. 46. Server-Side Events - Demo Demo - http://html5sse.cloudfoundry.com/ Source - https://github.com/zohararad/html5sse
    47. 47. Final Words Questions?
    48. 48. Zohar Aradwww.frontendworks.comwww.zohararad.com

    ×