Skip to content

wrandall22/xdomain

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

74 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

XDomain

Summary

A pure JavaScript CORS alternative. No server configuration required - just add a proxy.html on the domain you wish to communicate with. This library utilizes XHook to hook all XHR, so XDomain should work in conjunction with any library.

Features

  • Simple
  • Library Agnostic
    • Tested with jQuery $.ajax (and subsequently $.get, $.post)
    • Tested with Angular $http service
  • Cross domain XHR just magically works
  • Easy XHR access to file servers:
  • Includes XHook
  • White-list allowed domains
  • White-list paths using regular expressions (e.g. only allow API calls: /^\/api/)

Download

  • Development xdomain.js 16KB

  • Production xdomain.min.js 7.5KB (1.8KB Gzip)

    Note: It's important to include XDomain first as other libraries may store a reference to XMLHttpRequest before XHook can patch it

Live Demos

Browser Support

All except IE6/7 as they don't have postMessage

Quick Usage

  1. On your slave domain (http://xyz.example.com), create a small proxy.html file:

    <!DOCTYPE HTML>
    <script src="http://jpillora.com/xdomain/dist/0.5/xdomain.min.js" master="http://abc.example.com"></script>
  2. Then, on your master domain (http://abc.example.com), point to your new proxy.html:

    <script src="http://jpillora.com/xdomain/dist/0.5/xdomain.min.js" slave="http://xyz.example.com/proxy.html"></script>
  3. And that's it! Now, on your master domain, any XHR to http://xyz.example.com will automagically work:

    //do some vanilla XHR
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://xyz.example.com/secret/file.txt');
    xhr.onreadystatechange = function(e) {
      if(xhr.readyState === 4)
        alert(xhr.responseText);
    };
    xhr.send();
    
    //or if we are using jQuery...
    $.get('http://xyz.example.com/secret/file.txt').done(function(data) {
      console.log("got result: ", data);
    });

Tip: If you enjoy being standards compliant, you can also use data-master and data-slave attributes.

Using multiple masters and slaves

The following two snippets are equivalent:

<script src="http://jpillora.com/xdomain/dist/0.5/xdomain.min.js" master="http://abc.example.com"></script>
<script src="http://jpillora.com/xdomain/dist/0.5/xdomain.min.js"></script>
<script>
xdomain({
  masters: {
    'http://abc.example.com': /.*/
  }
});
</script>

So, we can then add more masters or (slaves) by simply including them in the object, see API below.

API

xdomain(object)

If object contains:

  • slaves

    Then xdomain will load as a master

    Each slave must be defined as: origin -> proxy file

    An object is used to list slaves to reinforce the idea that we need one proxy file per origin.

  • masters

    Then xdomain will load as a slave

    Each master must be defined as: origin -> allowed path (RegExp)

    origin will also be converted to a regular expression by escaping all non alphanumeric chars, converting * into .+ and wrapping with ^ and $.

    Requests that do not match both the origin and the path regular expressions will be blocked.

    So you could use the following proxy.html to allow all subdomains of example.com:

    <script src="/dist/0.5/xdomain.min.js" data-master="http://*.example.com"></script>

    Which is equivalent to:

    <script src="/dist/0.5/xdomain.min.js"></script>
    <script>
      xdomain({
        masters: {
          "http://*.example.com": /.*/
        }
      });
    </script>

    Therefore, you could allow ALL domains with the following proxy.html:

    <script src="/dist/0.5/xdomain.min.js" master="*"></script>

    Though this is NOT recommended.

Conceptual Overview

  1. XDomain will create an iframe on the master to the slave's proxy.
  2. Master will communicate to slave iframe using postMessage.
  3. Slave will create XHRs on behalf of master then return the results.

XHR interception is done seemlessly via XHook.

Internet Explorer

Use the HTML5 document type <!DOCTYPE HTML> to prevent your page from going into quirks mode. If you don't do this, XDomain will warn you about the missing JSON and/or postMessage globals and will exit.

FAQ

Q: But I love CORS

A: You shouldn't:

  • IE uses a different API (XDomainRequest) for CORS, XDomain normalizes this silliness.

  • On RESTful JSON API server, CORS will send a preflight OPTIONS request on all requests except for GET and HEAD, generating superfluous traffic.

  • Not everyone can change the HTTP headers on the server, but most people can drop in a proxy.html file.

  • Google also uses iframes as postMessage proxies instead of CORS in it's Google API JS SDK:

    <iframe name="oauth2relay564752183" id="oauth2relay564752183"
    src="https://accounts.google.com/o/oauth2/postmessageRelay?..."> </iframe>

Contributing

npm install -g grunt-source serve
git clone https://github.com/jpillora/xdomain
cd xdomain
grunt-source

Will start watching src for changes and will then compile and minify into dist

cd xdomain
serve

Visit http://localhost:3000

Issues and Pull-requests welcome.

Change Log

v0.5.0 - Upgraded to XHook v1.

v0.4.0 - Now setting request body, duh.

v0.3.0 - Moved to vanilla, using XHook to hook XHR instead of $.ajax

v0.2.0 - Removed PortHole, using pure postMessage, IE6/7 NOT supported

v0.1.0 - Alpha

MIT License

Copyright © 2013 Jaime Pillora <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

githalytics.com alpha

About

A pure JavaScript CORS alternative

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 84.8%
  • CoffeeScript 15.2%