CSSHttpRequest – cross browser AJAX without JSON

Because XMLHttpRequest only functions in a same-origin model, the main alternatives have been to either proxy the XML request server-side, or transfer javascript arrays via JSON (since cross-domain script calls are allowed). CSSHttpRequest is another method for performing cross-domain AJAX-style requests, but instead of running loading a remote Javascript file, CSS is used as the transport, and data is encoded inside of urls in @import statements.

A request is invoked using the CSSHttpRequest.get(url, callback) function:

    CSSHttpRequest.get(
        "http://www.nb.io/hacks/csshttprequest/hello-world/",
        function(response) { alert(response); }
    );

Data is encoded on the server into URI-encoded 2KB chunks and serialized into CSS @import rules with a modified about: URI scheme. The response is decoded and returned to the callback function as a string:

    @import url(about:chr:Hello%20World!);

CSSHttpRequest is open source under an Apache License (Version 2.0).

This is a pretty cool alternative—it seems to be a much safer way to do things than blindly executing javascript from servers not under your control. It’s somewhat like what XMLHttpRequest could have offered if it weren’t limited by the same-origin policy (though in a more roundabout way).

It still begs the question: why on earth is XMLHttpRequest limited by a same-origin policy, especially when it forces developers to adopt more dangerous methods for cross domain communication?

CSSHttpRequest

What will the next generation of Make: look like? We’re inviting you to shape the future by investing in Make:. By becoming an investor, you help decide what’s next. The future of Make: is in your hands. Learn More.

Discuss this article with the rest of the community on our Discord server!

ADVERTISEMENT

Escape to an island of imagination + innovation as Maker Faire Bay Area returns for its 16th iteration!

Prices Increase in....

Days
Hours
Minutes
Seconds
FEEDBACK