SlideShare a Scribd company logo
1 of 46
Download to read offline
Storage and Communication with
            HTML5
            Zohar Arad. March 2011
            zohar@zohararad.com | www.zohararad.com




Saturday, March 26, 2011                              1
We’re going to talk about

                  Cross-Origin Resource Sharing
                  Cross-Window message passing
                  Persistent data storage with localStorage
                  Persistent data storage with SQLite



Saturday, March 26, 2011                                      2
Cross-Origin Resource Sharing
            The evolution of XHR

Saturday, March 26, 2011                    3
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



Saturday, March 26, 2011                                                       4
This led to things like

                  JSONP
                  Flash-driven requests
                  Server-side proxy
                  Using iframes (express your frustration here)



Saturday, March 26, 2011                                          5
Thankfully,
                           these days are (nearly) gone




Saturday, March 26, 2011                                  6
Say Hello to CORS

Saturday, March 26, 2011        7
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



Saturday, March 26, 2011                                                    8
CORS - Client Side
             var xhr = new XMLHttpRequest();

             xhr.open(‘get’, ‘http://www.somesite.com/some_resource/’, true);

             xhr.onload = function(){       //instead of onreadystatechange

                           //do something

             };

             xhr.send(null);




Saturday, March 26, 2011                                                        9
Someone has to be different

Saturday, March 26, 2011                  10
CORS - Client Side (IE)
             var xhr = new XDomainRequest();

             xhr.open(‘get’, ‘http://www.somesite.com/some_resource/’);

             xhr.onload = function(){       //instead of onreadystatechange

                           //do something

             };

             xhr.send();




Saturday, March 26, 2011                                                      11
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


Saturday, March 26, 2011                                              12
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



Saturday, March 26, 2011                                                    13
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)


Saturday, March 26, 2011                                                           14
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




Saturday, March 26, 2011                                                         15
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




Saturday, March 26, 2011                                                      16
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)

Saturday, March 26, 2011                                                         17
Cross-Window Messaging
            Look Ma, no hacks

Saturday, March 26, 2011             18
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?



Saturday, March 26, 2011                                                19
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



Saturday, March 26, 2011                                               20
No more evil hacks
            postMessage brings balance to the force

Saturday, March 26, 2011                              21
Message passing


                  Evented
                  Sender / Receiver model
                  Receiver is responsible for enforcing security




Saturday, March 26, 2011                                           22
postMessage - Receiver
            window.addEventListener(“message”,onMessage,false);

            function onMessage(e){
              if(e.origin === ‘http://www.mydomain.com’){
                console.log(‘Got a message’,e.data);
              }
            }




Saturday, March 26, 2011                                          23
postMessage - Sender
            top.postMessage(‘Hi from iframe’,
                            ‘http://www.mydomain.com’);




Saturday, March 26, 2011                                  24
postMessage - Sending to iframes
            var el = document.getElementById(‘my_iframe’);

            var win = el.contentWindow;

            win.postMessage(‘Hi from iframe parent’,
                            ‘http://www.mydomain.com’);




Saturday, March 26, 2011                                     25
postMessage - Sending to popup
            var popup = window.open(......);

            popup.postMessage(‘Hi from iframe parent’,
                            ‘http://www.mydomain.com’);




Saturday, March 26, 2011                                  26
When should you use it?
                  Browser extensions
                  Embedded iframes (if you must use such evil)
                  Flash to Javascript




Saturday, March 26, 2011                                         27
Local Persistent Storage
            Goodbye Cookies

Saturday, March 26, 2011               28
Local Storage

                  Persistent key / value data store
                  Domain-specific
                  Limited to 5MB per domain
                  Not part of request
                  Completely cross-platform (yes, even IE7)


Saturday, March 26, 2011                                      29
localStorage - Basics
            var s = window.localStorage;

            s[‘somekey’] = ‘Some Value’;

            console.log(s[‘somekey’];




Saturday, March 26, 2011                   30
localStorage - API

                  getItem( key ) - get an item from data store
                  setItem( key, value ) - save item to data store
                  removeItem( key ) - remove item from data store
                  clear() - remove all items from data store



Saturday, March 26, 2011                                            31
localStorage - API
            Or you can use Javascript array notation:

            var s = window.localStorage;
            s.myItem = “My Value”;

            delete s.myItem;




Saturday, March 26, 2011                                32
localStorage - Internet Explorer 7
            var storage = document.createElement(‘var’);
            storage.style.behaviour = “url(‘#default#userData’)”;

            var b = document.getElementsByTagName(‘body’)[0];
            b.appendChild(storage);




Saturday, March 26, 2011                                            33
localStorage - Internet Explorer 7
            //setting a value
            var now = new Date();
            now.setYear(now.getYear() + 1);
            var expires = now.toUTCString();

            storage.setAttribute(“name”,”zohar”);
            storage.expires = expires;
            storage.save(“my_data_store”);




Saturday, March 26, 2011                            34
localStorage - Internet Explorer 7
            //getting a value

            storage.load(“my_data_store”);
            var v = storage.getAttribute(“name”);

            //removing a value
            storage.removeAttribute(“name”);
            storage.save(“my_data_store”);




Saturday, March 26, 2011                            35
localStorage - Internet Explorer 7


                  See http://msdn.microsoft.com/en-us/library/ms531424
                  (VS.85).aspx for a complete API reference
                  IE7 localStorage (data persistence) is limited to 128KB




Saturday, March 26, 2011                                                    36
Web Storage with SQLite
            Transactional offline data store

Saturday, March 26, 2011                      37
Web Storage

                  Transactional
                  Data-type aware
                  Supports complex data structures
                  No size limit
                  Works on WebKit, Opera (SQLite) and Firefox 4 (IndexedDB)


Saturday, March 26, 2011                                                      38
Web Storage - Why should you use it?

                  Browser-specific solutions (like extensions / apps)
                  Mobile browsers ?
                  Optimized data caching for offline access (did anyone say
                  mobile?)
                  Transactional operations


Saturday, March 26, 2011                                                     39
Web Storage - WebKit Example
            //create a DB and connect

            var            name = “app_db”;
            var            desc = “My Application DB”;
            var            ver = “1.0”;
            var            size = 10 * 1024 * 1024; // 10MB
            var            db = openDatabase(name,ver,desc,size);




Saturday, March 26, 2011                                            40
Web Storage - WebKit Example
            // create a table

            db.transaction(function (tx) {
              tx.executeSql(‘CREATE TABLE foo
                            (id unique, text)’);
            });




Saturday, March 26, 2011                           41
Web Storage - WebKit Example
            // insert some data

            db.transaction(function (tx) {
              tx.executeSql(‘insert into foo (text)
                            values ( ? )’,[“Hi There”]);
            });




Saturday, March 26, 2011                                   42
Web Storage - WebKit Example
            // read some data

            db.transaction(function (tx) {
              tx.executeSql(‘select * from foo where id > ?’, [10],
                function(tx,results){
                  var data = {};
                  for (var i = 0; i < results.rows.length; i++) {
                    var row = results.rows.item(i);
                    data[row.id] = row.text;
                  }
                  someCallback(data);
                });
            });
Saturday, March 26, 2011                                              43
Web Storage - WebKit Example
            // handle errors

            db.transaction(function (tx) {
              tx.executeSql(‘select * from foo where id > ?’, [10],
                 function(tx,results){
                    //... handle success
                 },
                 function(tx, errors){
                    //handle errors
                 }
              );
            });

Saturday, March 26, 2011                                              44
Resources
                  IndexedDB
                           http://www.html5rocks.com/tutorials/indexeddb/todo/
                           https://developer.mozilla.org/en/IndexedDB/IndexedDB_primer
                  Web SQL - http://www.html5rocks.com/tutorials/offline/storage/
                  CORS - http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-
                  with-cross-origin-resource-sharing/
                  Local Storage - http://html5tutorial.net/tutorials/working-with-html5-
                  localstorage.html

Saturday, March 26, 2011                                                                   45
Demo & Questions


                  Download demo from http://zohararad.com/sandbox/
                  cors.zip
                  gem install padrino
                  padrino start



Saturday, March 26, 2011                                             46

More Related Content

Similar to Cross Domain Access Policy solution using Cross Origin Resource sharing

It all starts with the ' (SQL injection from attacker's point of view)
It all starts with the ' (SQL injection from attacker's point of view)It all starts with the ' (SQL injection from attacker's point of view)
It all starts with the ' (SQL injection from attacker's point of view)Miroslav Stampar
 
Node.js and websockets intro
Node.js and websockets introNode.js and websockets intro
Node.js and websockets introkompozer
 
Browser security
Browser securityBrowser security
Browser securityUday Anand
 
Defending Against Application DoS attacks
Defending Against Application DoS attacksDefending Against Application DoS attacks
Defending Against Application DoS attacksRoberto Suggi Liverani
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a BottleZohar Arad
 
Scalable Web Solutions - Use Case: Regulatory Reform In Vietnam On eZ Publish...
Scalable Web Solutions - Use Case: Regulatory Reform In Vietnam On eZ Publish...Scalable Web Solutions - Use Case: Regulatory Reform In Vietnam On eZ Publish...
Scalable Web Solutions - Use Case: Regulatory Reform In Vietnam On eZ Publish...Ivo Lukač
 
Scaling the Britain's Got Talent Buzzer
Scaling the Britain's Got Talent BuzzerScaling the Britain's Got Talent Buzzer
Scaling the Britain's Got Talent BuzzerMalcolm Box
 
Buried by time, dust and BeEF
Buried by time, dust and BeEFBuried by time, dust and BeEF
Buried by time, dust and BeEFMichele Orru
 
HTML5: Building the Next Generation of Web Applications
HTML5: Building the Next Generation of Web ApplicationsHTML5: Building the Next Generation of Web Applications
HTML5: Building the Next Generation of Web ApplicationsChrome Developer Relations
 
Apache ActiveMQ and Apache ServiceMix
Apache ActiveMQ and Apache ServiceMixApache ActiveMQ and Apache ServiceMix
Apache ActiveMQ and Apache ServiceMixBruce Snyder
 
Microservices vs monolithic
Microservices vs monolithicMicroservices vs monolithic
Microservices vs monolithicXuân-Lợi Vũ
 
Browser Internals-Same Origin Policy
Browser Internals-Same Origin PolicyBrowser Internals-Same Origin Policy
Browser Internals-Same Origin PolicyKrishna T
 
Got database access? Own the network!
Got database access? Own the network!Got database access? Own the network!
Got database access? Own the network!Bernardo Damele A. G.
 
SeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocket
SeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocketSeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocket
SeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocketProcessOne
 

Similar to Cross Domain Access Policy solution using Cross Origin Resource sharing (18)

It all starts with the ' (SQL injection from attacker's point of view)
It all starts with the ' (SQL injection from attacker's point of view)It all starts with the ' (SQL injection from attacker's point of view)
It all starts with the ' (SQL injection from attacker's point of view)
 
Node.js and websockets intro
Node.js and websockets introNode.js and websockets intro
Node.js and websockets intro
 
Html5 apis
Html5 apisHtml5 apis
Html5 apis
 
What's New in GWT 2.2
What's New in GWT 2.2What's New in GWT 2.2
What's New in GWT 2.2
 
Browser security
Browser securityBrowser security
Browser security
 
Defending Against Application DoS attacks
Defending Against Application DoS attacksDefending Against Application DoS attacks
Defending Against Application DoS attacks
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a Bottle
 
Scalable Web Solutions - Use Case: Regulatory Reform In Vietnam On eZ Publish...
Scalable Web Solutions - Use Case: Regulatory Reform In Vietnam On eZ Publish...Scalable Web Solutions - Use Case: Regulatory Reform In Vietnam On eZ Publish...
Scalable Web Solutions - Use Case: Regulatory Reform In Vietnam On eZ Publish...
 
Scaling the Britain's Got Talent Buzzer
Scaling the Britain's Got Talent BuzzerScaling the Britain's Got Talent Buzzer
Scaling the Britain's Got Talent Buzzer
 
Buried by time, dust and BeEF
Buried by time, dust and BeEFBuried by time, dust and BeEF
Buried by time, dust and BeEF
 
HTML5: Building the Next Generation of Web Applications
HTML5: Building the Next Generation of Web ApplicationsHTML5: Building the Next Generation of Web Applications
HTML5: Building the Next Generation of Web Applications
 
Apache ActiveMQ and Apache ServiceMix
Apache ActiveMQ and Apache ServiceMixApache ActiveMQ and Apache ServiceMix
Apache ActiveMQ and Apache ServiceMix
 
Microservices vs monolithic
Microservices vs monolithicMicroservices vs monolithic
Microservices vs monolithic
 
Browser Internals-Same Origin Policy
Browser Internals-Same Origin PolicyBrowser Internals-Same Origin Policy
Browser Internals-Same Origin Policy
 
Got database access? Own the network!
Got database access? Own the network!Got database access? Own the network!
Got database access? Own the network!
 
SeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocket
SeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocketSeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocket
SeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocket
 
Securing Your API
Securing Your APISecuring Your API
Securing Your API
 
Ruby on-rails-security
Ruby on-rails-securityRuby on-rails-security
Ruby on-rails-security
 

Recently uploaded

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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 interpreternaman860154
 

Recently uploaded (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 

Cross Domain Access Policy solution using Cross Origin Resource sharing

  • 1. Storage and Communication with HTML5 Zohar Arad. March 2011 zohar@zohararad.com | www.zohararad.com Saturday, March 26, 2011 1
  • 2. We’re going to talk about Cross-Origin Resource Sharing Cross-Window message passing Persistent data storage with localStorage Persistent data storage with SQLite Saturday, March 26, 2011 2
  • 3. Cross-Origin Resource Sharing The evolution of XHR Saturday, March 26, 2011 3
  • 4. 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 Saturday, March 26, 2011 4
  • 5. This led to things like JSONP Flash-driven requests Server-side proxy Using iframes (express your frustration here) Saturday, March 26, 2011 5
  • 6. Thankfully, these days are (nearly) gone Saturday, March 26, 2011 6
  • 7. Say Hello to CORS Saturday, March 26, 2011 7
  • 8. 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 Saturday, March 26, 2011 8
  • 9. CORS - Client Side var xhr = new XMLHttpRequest(); xhr.open(‘get’, ‘http://www.somesite.com/some_resource/’, true); xhr.onload = function(){ //instead of onreadystatechange //do something }; xhr.send(null); Saturday, March 26, 2011 9
  • 10. Someone has to be different Saturday, March 26, 2011 10
  • 11. CORS - Client Side (IE) var xhr = new XDomainRequest(); xhr.open(‘get’, ‘http://www.somesite.com/some_resource/’); xhr.onload = function(){ //instead of onreadystatechange //do something }; xhr.send(); Saturday, March 26, 2011 11
  • 12. 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 Saturday, March 26, 2011 12
  • 13. 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 Saturday, March 26, 2011 13
  • 14. 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) Saturday, March 26, 2011 14
  • 15. 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 Saturday, March 26, 2011 15
  • 16. 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 Saturday, March 26, 2011 16
  • 17. 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) Saturday, March 26, 2011 17
  • 18. Cross-Window Messaging Look Ma, no hacks Saturday, March 26, 2011 18
  • 19. 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? Saturday, March 26, 2011 19
  • 20. 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 Saturday, March 26, 2011 20
  • 21. No more evil hacks postMessage brings balance to the force Saturday, March 26, 2011 21
  • 22. Message passing Evented Sender / Receiver model Receiver is responsible for enforcing security Saturday, March 26, 2011 22
  • 23. postMessage - Receiver window.addEventListener(“message”,onMessage,false); function onMessage(e){ if(e.origin === ‘http://www.mydomain.com’){ console.log(‘Got a message’,e.data); } } Saturday, March 26, 2011 23
  • 24. postMessage - Sender top.postMessage(‘Hi from iframe’, ‘http://www.mydomain.com’); Saturday, March 26, 2011 24
  • 25. postMessage - Sending to iframes var el = document.getElementById(‘my_iframe’); var win = el.contentWindow; win.postMessage(‘Hi from iframe parent’, ‘http://www.mydomain.com’); Saturday, March 26, 2011 25
  • 26. postMessage - Sending to popup var popup = window.open(......); popup.postMessage(‘Hi from iframe parent’, ‘http://www.mydomain.com’); Saturday, March 26, 2011 26
  • 27. When should you use it? Browser extensions Embedded iframes (if you must use such evil) Flash to Javascript Saturday, March 26, 2011 27
  • 28. Local Persistent Storage Goodbye Cookies Saturday, March 26, 2011 28
  • 29. Local Storage Persistent key / value data store Domain-specific Limited to 5MB per domain Not part of request Completely cross-platform (yes, even IE7) Saturday, March 26, 2011 29
  • 30. localStorage - Basics var s = window.localStorage; s[‘somekey’] = ‘Some Value’; console.log(s[‘somekey’]; Saturday, March 26, 2011 30
  • 31. localStorage - API getItem( key ) - get an item from data store setItem( key, value ) - save item to data store removeItem( key ) - remove item from data store clear() - remove all items from data store Saturday, March 26, 2011 31
  • 32. localStorage - API Or you can use Javascript array notation: var s = window.localStorage; s.myItem = “My Value”; delete s.myItem; Saturday, March 26, 2011 32
  • 33. localStorage - Internet Explorer 7 var storage = document.createElement(‘var’); storage.style.behaviour = “url(‘#default#userData’)”; var b = document.getElementsByTagName(‘body’)[0]; b.appendChild(storage); Saturday, March 26, 2011 33
  • 34. localStorage - Internet Explorer 7 //setting a value var now = new Date(); now.setYear(now.getYear() + 1); var expires = now.toUTCString(); storage.setAttribute(“name”,”zohar”); storage.expires = expires; storage.save(“my_data_store”); Saturday, March 26, 2011 34
  • 35. localStorage - Internet Explorer 7 //getting a value storage.load(“my_data_store”); var v = storage.getAttribute(“name”); //removing a value storage.removeAttribute(“name”); storage.save(“my_data_store”); Saturday, March 26, 2011 35
  • 36. localStorage - Internet Explorer 7 See http://msdn.microsoft.com/en-us/library/ms531424 (VS.85).aspx for a complete API reference IE7 localStorage (data persistence) is limited to 128KB Saturday, March 26, 2011 36
  • 37. Web Storage with SQLite Transactional offline data store Saturday, March 26, 2011 37
  • 38. Web Storage Transactional Data-type aware Supports complex data structures No size limit Works on WebKit, Opera (SQLite) and Firefox 4 (IndexedDB) Saturday, March 26, 2011 38
  • 39. Web Storage - Why should you use it? Browser-specific solutions (like extensions / apps) Mobile browsers ? Optimized data caching for offline access (did anyone say mobile?) Transactional operations Saturday, March 26, 2011 39
  • 40. Web Storage - WebKit Example //create a DB and connect var name = “app_db”; var desc = “My Application DB”; var ver = “1.0”; var size = 10 * 1024 * 1024; // 10MB var db = openDatabase(name,ver,desc,size); Saturday, March 26, 2011 40
  • 41. Web Storage - WebKit Example // create a table db.transaction(function (tx) {   tx.executeSql(‘CREATE TABLE foo (id unique, text)’); }); Saturday, March 26, 2011 41
  • 42. Web Storage - WebKit Example // insert some data db.transaction(function (tx) {   tx.executeSql(‘insert into foo (text) values ( ? )’,[“Hi There”]); }); Saturday, March 26, 2011 42
  • 43. Web Storage - WebKit Example // read some data db.transaction(function (tx) {   tx.executeSql(‘select * from foo where id > ?’, [10], function(tx,results){ var data = {}; for (var i = 0; i < results.rows.length; i++) { var row = results.rows.item(i); data[row.id] = row.text; } someCallback(data); }); }); Saturday, March 26, 2011 43
  • 44. Web Storage - WebKit Example // handle errors db.transaction(function (tx) {   tx.executeSql(‘select * from foo where id > ?’, [10], function(tx,results){ //... handle success }, function(tx, errors){ //handle errors } ); }); Saturday, March 26, 2011 44
  • 45. Resources IndexedDB http://www.html5rocks.com/tutorials/indexeddb/todo/ https://developer.mozilla.org/en/IndexedDB/IndexedDB_primer Web SQL - http://www.html5rocks.com/tutorials/offline/storage/ CORS - http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax- with-cross-origin-resource-sharing/ Local Storage - http://html5tutorial.net/tutorials/working-with-html5- localstorage.html Saturday, March 26, 2011 45
  • 46. Demo & Questions Download demo from http://zohararad.com/sandbox/ cors.zip gem install padrino padrino start Saturday, March 26, 2011 46