SlideShare a Scribd company logo
Message in a bottle
Client-Client and Client-Server communication with HTML5



Zohar 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)
Desktop Notifications
Integrating the browser with the desktop
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 Messaging
Look Ma, no hacks
Posting messages between windows


We have two windows under our control
They don’t necessarily reside under the same domain
How can we pass messages from one window to the
other?
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 hacks
postMessage brings balance to the force
Message passing


Evented
Sender / Receiver model
Receiver is responsible for enforcing security
postMessage - Receiver
window.addEventListener(“message”,onMessage,false);

function onMessage(e){
  if(e.origin === ‘http://www.mydomain.com’){
    console.log(‘Got a message’,e.data);
  }
}
postMessage - Sender
top.postMessage(‘Hi from iframe’,
                ‘http://www.mydomain.com’);
postMessage - Sending to iframes
var el = document.getElementById(‘my_iframe’);

var win = el.contentWindow;

win.postMessage(‘Hi from iframe parent’,
                ‘http://www.mydomain.com’);
postMessage - Sending to popup
var 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 Sharing
The 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 AJAX

Cross-domain requests are allowed
Server is responsible for defining the security policy
Client is responsible for enforcing the security policy
Works over standard HTTP
CORS - Client Side
var 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 Side
Access-Control-Allow-Origin: http://www.somesite.com/some_resource

Access-Control-Allow-Methods: POST, GET

Access-Control-Allow-Headers: NCZ

Access-Control-Max-Age: 84600

Access-Control-Allow-Credentials: true
CORS - Recap
Client sends a CORS request to the server
Server checks request headers for access control
according to URI, method, headers and credentials
Server responds to client with an access control response
Client 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 Events
Message 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 - Client
source.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 Arad

www.frontendworks.com
www.zohararad.com

More Related Content

PDF
Security in php
ODP
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
PDF
Rest Security with JAX-RS
PPT
Scalable Reliable Secure REST
PPT
Synapseindia dot net development web applications with ajax
PPTX
REST API Design for JAX-RS And Jersey
PDF
Node.js introduction
PPTX
Web services101
Security in php
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Rest Security with JAX-RS
Scalable Reliable Secure REST
Synapseindia dot net development web applications with ajax
REST API Design for JAX-RS And Jersey
Node.js introduction
Web services101

What's hot (20)

PPT
PowerShell Technical Overview
PDF
Spring Web Services: SOAP vs. REST
PPTX
Playing with cxf interceptor in mule
PPTX
Web services - A Practical Approach
PPTX
Playing with cxf interceptor in mule
PPTX
IBM Connect 2016 - Break out of the Box
PPTX
Break out of The Box - Part 2
PPT
JSON Rules Language
PDF
AD102 - Break out of the Box
KEY
Socket.io
PDF
JWT - Sécurisez vos APIs
PPTX
Ws security with mule
PPTX
Building Web Apps with Express
PDF
Servlet sessions
PDF
SOAP-based Web Services
PDF
Servlets intro
PDF
PPT
Node js Modules and Event Emitters
PPTX
Build a Node.js Client for Your REST+JSON API
PPTX
ASP.NET WEB API Training
PowerShell Technical Overview
Spring Web Services: SOAP vs. REST
Playing with cxf interceptor in mule
Web services - A Practical Approach
Playing with cxf interceptor in mule
IBM Connect 2016 - Break out of the Box
Break out of The Box - Part 2
JSON Rules Language
AD102 - Break out of the Box
Socket.io
JWT - Sécurisez vos APIs
Ws security with mule
Building Web Apps with Express
Servlet sessions
SOAP-based Web Services
Servlets intro
Node js Modules and Event Emitters
Build a Node.js Client for Your REST+JSON API
ASP.NET WEB API Training
Ad

Viewers also liked (6)

PDF
Rolling Your Own CSS Methodology
PPT
CSS Methodology
PPT
Javascript Design Patterns
KEY
Architecting single-page front-end apps
KEY
Introduction to HAML
PDF
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
Rolling Your Own CSS Methodology
CSS Methodology
Javascript Design Patterns
Architecting single-page front-end apps
Introduction to HAML
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
Ad

Similar to Message in a Bottle (20)

PDF
Using Communication and Messaging API in the HTML5 World
PDF
Cross Domain Access Policy solution using Cross Origin Resource sharing
PDF
HTML5 storage and communication - Zohar Arad
PDF
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
PDF
Javascript cross domain communication
PDF
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
PPT
Breaking The Cross Domain Barrier
PDF
HTML5 Server Sent Events/JSF JAX 2011 Conference
PDF
HTML5/JavaScript Communication APIs - DPC 2014
PDF
Server-Side Programming Primer
PPT
HTTP protocol and Streams Security
PDF
Cors michael
PPTX
5 x HTML5 worth using in APEX (5)
PPTX
Stay Out Please
PPTX
W3 conf hill-html5-security-realities
PDF
Cross site calls with javascript - the right way with CORS
PDF
Pushing the Web: Interesting things to Know
PDF
Web architecturesWeb architecturesWeb architectures
PPTX
Secure web messaging in HTML5
PDF
The Same-Origin Policy
Using Communication and Messaging API in the HTML5 World
Cross Domain Access Policy solution using Cross Origin Resource sharing
HTML5 storage and communication - Zohar Arad
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Javascript cross domain communication
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
Breaking The Cross Domain Barrier
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5/JavaScript Communication APIs - DPC 2014
Server-Side Programming Primer
HTTP protocol and Streams Security
Cors michael
5 x HTML5 worth using in APEX (5)
Stay Out Please
W3 conf hill-html5-security-realities
Cross site calls with javascript - the right way with CORS
Pushing the Web: Interesting things to Know
Web architecturesWeb architecturesWeb architectures
Secure web messaging in HTML5
The Same-Origin Policy

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
sap open course for s4hana steps from ECC to s4
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Big Data Technologies - Introduction.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Building Integrated photovoltaic BIPV_UPV.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Unlocking AI with Model Context Protocol (MCP)
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
sap open course for s4hana steps from ECC to s4
“AI and Expert System Decision Support & Business Intelligence Systems”
Diabetes mellitus diagnosis method based random forest with bat algorithm
The AUB Centre for AI in Media Proposal.docx
Reach Out and Touch Someone: Haptics and Empathic Computing
MYSQL Presentation for SQL database connectivity
Understanding_Digital_Forensics_Presentation.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Big Data Technologies - Introduction.pptx

Message in a Bottle

  • 1. Message in a bottle Client-Client and Client-Server communication with HTML5 Zohar Arad. October 2011
  • 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. 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. Desktop Notifications Integrating the browser with the desktop
  • 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. 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. 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. 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. Desktop Notifications - API show - Show a created notification cancel - Hide a created notification
  • 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
  • 12. Posting messages between windows We have two windows under our control They don’t necessarily reside under the same domain How can we pass messages from one window to the other?
  • 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. No more evil hacks postMessage brings balance to the force
  • 15. Message passing Evented Sender / Receiver model Receiver is responsible for enforcing security
  • 16. postMessage - Receiver window.addEventListener(“message”,onMessage,false); function onMessage(e){ if(e.origin === ‘http://www.mydomain.com’){ console.log(‘Got a message’,e.data); } }
  • 17. postMessage - Sender top.postMessage(‘Hi from iframe’, ‘http://www.mydomain.com’);
  • 18. postMessage - Sending to iframes var el = document.getElementById(‘my_iframe’); var win = el.contentWindow; win.postMessage(‘Hi from iframe parent’, ‘http://www.mydomain.com’);
  • 19. postMessage - Sending to popup var popup = window.open(......); popup.postMessage(‘Hi from iframe parent’, ‘http://www.mydomain.com’);
  • 20. When should you use it? Browser extensions Embedded iframes (if you must use such evil) Flash to Javascript
  • 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. This led to things like JSONP Flash-driven requests Server-side proxy Using iframes (express your frustration here)
  • 24. Thankfully, these days are (nearly) gone
  • 25. Say Hello to CORS
  • 26. CORS is the new AJAX Cross-domain requests are allowed Server is responsible for defining the security policy Client is responsible for enforcing the security policy Works over standard HTTP
  • 27. CORS - Client Side var xhr = new XMLHttpRequest(); xhr.open(‘get’, ‘http://www.somesite.com/some_resource/’, true); xhr.onload = function(){ //instead of onreadystatechange }; xhr.send(null);
  • 28. Someone has to be different
  • 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. 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. 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. 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. CORS - Server Side Access-Control-Allow-Origin: http://www.somesite.com/some_resource Access-Control-Allow-Methods: POST, GET Access-Control-Allow-Headers: NCZ Access-Control-Max-Age: 84600 Access-Control-Allow-Credentials: true
  • 34. CORS - Recap Client sends a CORS request to the server Server checks request headers for access control according to URI, method, headers and credentials Server responds to client with an access control response Client decides whether to send the request or not
  • 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)
  • 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. 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. Server-Side Events - Client source.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. Server-Side Events - Server data: Hi Everyonen id: 12345n data: {msg:"Hello HTML5Fest"} retry: 5000n data: rety menn
  • 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. Server-Side Events - Server Response content-type should be text/event-steam Flush buffer after every chunk Keep the connection open
  • 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. 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. 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. Server-Side Events - Demo Demo - http://html5sse.cloudfoundry.com/ Source - https://github.com/zohararad/html5sse

Editor's Notes