///Forcing client side cross-domain HTTP requests with JavaScript

Forcing client side cross-domain HTTP requests with JavaScript

When putting together your web application, there are a number of reasons why you might want to force some HTTP requests. For example, Facebook recently scaled their new Facebook Chat feature from 0 to 70 million users overnight, by thoroughly load testing it with silent HTTP requests from clients. You might also want to record a request on a target page on another domain. In this mini tutorial, I’ll show you how to force client-side HTTP requests using pure JavaScript.

JavaScript is essentially a means with which to programmatically control the browser. However, there are a number of security restrictions in place the moment you want to hit the network. AJAX is disabled across domains to prevent allowing a particular website force its clients to download pages from another. So, if you are running JavaScript on abc.example.com and try to make an AJAX request to example2.com, the browser will promptly throw an error.

However, if the actual request information is unimportant, and we simply want to simulate the HTTP request, there is a way around this: forcing an image download. To allow image preloading through JavaScript, so that images are not downloaded on the fly, JavaScript includes an Image() class. When we create a new Image() object, the browser creates an internal image just like any other image on the page. If we set an “src” property of the object, with a URL pointing to the location of the image file, the browser will start downloading the resource — content type be damned.

Here’s a quick demo script:

var myResource = new Image();
myResource.src = "somefile.html";

The moment this is executed, somefile.html will be downloaded from the server. Try it out, and watch the HTTP request fly past (Firebug’s Net panel or Firefox’s LiveHttpHeaders extension are handy here). The URI doesn’t have to be relative, either. It works perfectly cross-domain:

There are a few drawbacks to this approach. The first is, of course, that we can’t work with the data fetched through the request — just as we can’t work with the binary data of an image (nor would we want to). Second, there is no real mechanism to monitor the request – not even HTTP status codes. Of course, this isn’t a problem if you have total control over the server at the other end.

So the next time you need to force a cross-domain client side HTTP request, just try a snippet of Javascript – this image preload hack might be just what you need.

2008-06-22T06:29:17+00:00 June 22nd, 2008|JavaScript|0 Comments

About the Author:

Leave A Comment