SlideShare uma empresa Scribd logo
1 de 48
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

Mais conteúdo relacionado

Mais procurados

JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
giurca
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
vantinhkhuc
 

Mais procurados (20)

PowerShell Technical Overview
PowerShell Technical OverviewPowerShell Technical Overview
PowerShell Technical Overview
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Playing with cxf interceptor in mule
Playing with cxf interceptor in mulePlaying with cxf interceptor in mule
Playing with cxf interceptor in mule
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
 
Playing with cxf interceptor in mule
Playing with cxf interceptor in mulePlaying with cxf interceptor in mule
Playing with cxf interceptor in mule
 
IBM Connect 2016 - Break out of the Box
IBM Connect 2016 - Break out of the BoxIBM Connect 2016 - Break out of the Box
IBM Connect 2016 - Break out of the Box
 
Break out of The Box - Part 2
Break out of The Box - Part 2Break out of The Box - Part 2
Break out of The Box - Part 2
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
Socket.io
Socket.ioSocket.io
Socket.io
 
JWT - Sécurisez vos APIs
JWT - Sécurisez vos APIsJWT - Sécurisez vos APIs
JWT - Sécurisez vos APIs
 
Ws security with mule
Ws security with muleWs security with mule
Ws security with mule
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
SOAP-based Web Services
SOAP-based Web ServicesSOAP-based Web Services
SOAP-based Web Services
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Build a Node.js Client for Your REST+JSON API
Build a Node.js Client for Your REST+JSON APIBuild a Node.js Client for Your REST+JSON API
Build a Node.js Client for Your REST+JSON API
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 

Destaque

CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
Zohar Arad
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Zohar Arad
 
Architecting single-page front-end apps
Architecting single-page front-end appsArchitecting single-page front-end apps
Architecting single-page front-end apps
Zohar Arad
 

Destaque (6)

Rolling Your Own CSS Methodology
Rolling Your Own CSS MethodologyRolling Your Own CSS Methodology
Rolling Your Own CSS Methodology
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Architecting single-page front-end apps
Architecting single-page front-end appsArchitecting single-page front-end apps
Architecting single-page front-end apps
 
Introduction to HAML
Introduction to HAMLIntroduction to HAML
Introduction to HAML
 
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
 

Semelhante a Message in a Bottle

A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
Pentesting web applications
Pentesting web applicationsPentesting web applications
Pentesting web applications
Satish b
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
Cosmin Mereuta
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
Ismael Celis
 

Semelhante a Message in a Bottle (20)

Pushing the Web: Interesting things to Know
Pushing the Web: Interesting things to KnowPushing the Web: Interesting things to Know
Pushing the Web: Interesting things to Know
 
Browser security
Browser securityBrowser security
Browser security
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
 
Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time Communications
 
08 ajax
08 ajax08 ajax
08 ajax
 
Browser Security
Browser SecurityBrowser Security
Browser Security
 
Building Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 FeaturesBuilding Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 Features
 
SocketStream
SocketStreamSocketStream
SocketStream
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Pentesting web applications
Pentesting web applicationsPentesting web applications
Pentesting web applications
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
Secure java script-for-developers
Secure java script-for-developersSecure java script-for-developers
Secure java script-for-developers
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

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

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n