23 Mar 2016

XDomain

Why XDomain ?

Cross-Site request (request for resources located on a different domain than the source of the request) initiated by a JavaScript are restricted for security reason. The W3C has produced a recommendation for the Cross-Site Resource Sharing (CORS), this specification uses XMLHttpRequest for the API Request and supply to the web server an access for the cross-site and so provide a security transfer.

IE8 and IE9 does not support the XMLHttpRequest cross-site, Jaime Pillora has developed a solution called XDomain which work like a Javascript proxy for the API Request. The limit to this solution is that you needed access to the API to use (or it use already XDomain) and on the JavaScript application. An other solution is use directly XDomainRequest available on IE8 and IE9, the advantage to use XDomain is than you do not have to manage in your code call in XMLHttpRequest and XDomainRequest.

How does it work?

 

  1. XDomain create an iframe on your application (master) toward the API’s Proxy (slave)
  2. The application will communicate to API iframe using postMessage
  3. API create a XMLHttpRequest response on behalf of master

XHR interception is done via XHook, developed by Jaime Pilora.

XDomain is available on Jaime Pilora’s GitHub: https://github.com/jpillora/xdomain

How to use it?

API Side :

API must be returns a proxy.html file, the simplest is to create it on the root site. The proxy.html file contains only the XDomain’s JavaScript and the attribute “data-master”. This attribute is used to filter authorized domain. The value “*” authorize all domains is not recommended. If you use several domains, you can configured in JavaScript with “xdomain.master”(see ‘Application Side’ for the sample).

sample :

Application Side:

In the page must be called the API or in a layout page, use XDomain and configure the API (slave). In the sample below we make it in JavaScript to configure several API, but if you use only one API you can use attribute “data-slave”. The property slave defines the proxy to use.

sample :

 

Share