27 Apr

Enabling Cross Domain Ajax Requests using CORS

Okay, I usually harped about the one main limitation of Ajax Requests – Same Origin Policy. This policy exists to restrict XSS (Cross Site Scripting) attacks and vulnerabilities. But that is also a big party pooper when you want to legally make an Ajax call from your site to another domain, directly from the browser in order to load content from the other domain. There are exceptions to this policy that allow for embedding of certain resources like images, scripts, stylesheets, media and some other types of content. Thus CDNs for loading scripts like jQuery and stylesheets from Bootstrap are quite common and actually recommended too. But that’s not Ajax. Ajax begins when an XMLHttpRequest object is created. And that object cannot normally be used to make a request to any other domain other than the one it is currently on.

Same Origin Policy

For example, if a script on a page on the domain http://DomainA.com wants make an Ajax request, it is limited to make the request to any resource only on the http://DomainA.com domain by the Same Origin Policy.  If the script tries to make a request to http://DomainB.com, it will be actively blocked by the browser. The policy applies to Port numbers, sub-domains and protocols too. This is a good thing to protect users from visiting untrusted sites and having those sites steal the users sessions from trusted websites. But to legally make a script load content from another domain, say like your recent tweets, your facebook posts or your flickr feed or weather data or stock info from an online API or Web Service, this policy restricts you to adopting one of the following techniques to achieve your goal:

  • Use a Server Side Proxy
  • Use JSONP (if the remote API supports it)

I will leave the JSONP technique for another day and get to my subject now. The W3C made CORS (Cross Origin Resource Sharing) a Recommendation in January 2014, a document that was in the works for some time now.

The CORS Recommendation allows a way around for web servers to allow for cross domain script requests. Servers can now do this by adding new headers in the HTTP response to a cross domain request, namely:

By sending this new header, the server can let the browser making the request know that it can allow the request and response to be used by the script, and hence not block the request. You can read more details about the CORS spec on W3.org and MDN. This is great for API developers who want to make a service available for consumption from simple Ajax requests from any domain.

I will jump to my demo now. https://sreenath.net/demos/CORSDemo.htm

To demonstrate this, I use the OpenWeatherMap’s REST API to provide me the cross domain content. And I use a standard XMLHttpRequest object pointed to the Open Weather Map API’s URL for retrieving the current weather data for the requested city.

For example, if I want to get the current weather conditions of New York, NY, my XHR’s URL will look like this:

and my request headers (on chrome) look like this:

And the response headers from the server look like this:

Yep, a 200 OK response alright. And since I didn’t specify a format, I would receive the default JSON format from the server containing the current weather conditions.

Observe the last three response headers. They are all from the CORS spec and there are more. To go deeper into this topic, Monsur Hossain has published a book “CORS In Action“, available Sept 2014 in print or now through MEAP. You can also visit Enable CORS website to get updated information and use this link to know about browser support for this new spec.

With ASP.NET Web API where it currently is, this development greatly enhances the idea of Service Oriented Applications and also emphasizes the role of JavaScript in the world of programming today. Get cracking!

Questions? Comment below ↓

03 Apr

JavaScript Animations and HTML5 Vibration APIs

HTML5 Logo

First checkout this demo link on your cell phone: https://sreenath.net/demos/animation.htm

On a normal desktop browser with no Vibration hardware, you will see a ball simply bouncing on a black background. On a device with Vibration hardware and a supporting browser, you will feel the ball bounce off the sides of the window with a short vibration.

That’s new in HTML5 and JavaScript. Here how its done:

It’s that simple. 100 here is the duration to vibrate. You can also pass in an array of milliseconds, duration of vibration followed by duration of silence and so on as follows:

Now about timing the vibrations with the animation:

I use a JSON object as a Singleton for storing data about the window height, width, position of the ball, direction etc.

I have the following event handlers attached to the window load event and the window resize event: (Note that this code wont gracefully degrade in IE8 and older browsers)

My startAnimation function:

It is important that the CSS for the box1 object to move is to set its position as absolute. Otherwise the best code won’t work on it. So here’s the CSS:

Finally my Animate function.

Its important to update the direction of the movement of the box once it hits the edge and to check the direction each time before moving the box to determine which way it should be headed – to decide whether to increment or decrement the left/top property.

And my setDimensions function, required for initial loading and handling browser resize events:

Known Issues with the demo:

  1. Doesn’t handle resize due to re-orientation event of your device.
  2. As of publishing time,  Safari doesn’t support the Vibration API. That leaves out all iOS devices from enjoying this demo.