Giter Site home page Giter Site logo

xdomain's Introduction

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 will work seamlessly with any library.

Features

  • Simple
  • Library Agnostic
    • With jQuery $.ajax (and subsequently $.get, $.post)
    • With Angular $http service
  • Cross domain XHR just magically works
  • Easy XHR access to file servers:
  • Includes XHook and its features
  • proxy.html files (slaves) may:
    • White-list domains
    • White-list paths using regular expressions (e.g. only allow API calls: /^\/api/)
  • Highly performant
  • Seamless integration with FormData
  • Supports RequiresJS and Browserify

Download

Live Demos

Browser Support

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

Quick Usage

Note: It's important to include XDomain before any other library. When XDomain loads, XHook replaces the current window.XMLHttpRequest. So if another library saves a reference to the original window.XMLHttpRequest and uses that, XHook won't be able to intercept those requests.

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

    <!DOCTYPE HTML>
    <script src="//unpkg.com/[email protected]/dist/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="//unpkg.com/[email protected]/dist/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) console.log("got result: ", 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="//unpkg.com/[email protected]/dist/xdomain.min.js" master="http://abc.example.com/api/*"></script>
<script src="//unpkg.com/[email protected]/dist/xdomain.min.js"></script>
<script>
xdomain.masters({
  'http://abc.example.com': '/api/*'
});
</script>

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

API

xdomain.slaves(slaves)

Will initialize as a master

Each of the slaves must be defined as: origin: proxy file

The slaves object is used as a list slaves to force one proxy file per origin.

The Quick Usage step 2 above is equivalent to:

<script src="//unpkg.com/[email protected]/dist/xdomain.min.js"></script>
<script>
  xdomain.slaves({
    "http://xyz.example.com": "/proxy.html"
  });
</script>

xdomain.masters(masters)

Will initialize as a slave

Each of the masters must be defined as: origin: path

origin and path are converted to a regular expression by escaping all non-alphanumeric chars, then converting * into .* and finally wrapping it with ^ and $. path can also be a RegExp literal.

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/xdomain.min.js" data-master="http://*.example.com/api/*.json"></script>

Which is equivalent to:

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

Where "/api/*.json" becomes the RegExp /^\/api\/.*\.json$/

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

<!-- BEWARE: VERY INSECURE -->
<script src="/dist/xdomain.min.js" master="*"></script>

xdomain.debug = false

When true, XDomain will log actions to console

xdomain.timeout = 15e3ms (15 seconds)

Number of milliseconds until XDomains gives up waiting for an iframe to respond

xdomain.on(event, handler)

event may be log, warn or timeout. When listening for log and warn events, handler with contain the message as the first parameter. The timeout event fires when an iframe exeeds the xdomain.timeout time limit.

xdomain.cookies

WARNING ⚠️ Chrome and possibly other browsers appear to be blocking access to the iframe's document.cookie property. This means Slave-Cookies are no longer supported in some browsers.

When withCredentials is set to true for a given request, the cookies of the master and slave are sent to the server using these names. If one is set to null, it will not be sent.

//defaults
xdomain.cookies = {
  master: "Master-Cookie"
  slave: "Slave-Cookie"
};

Note, if you use "Cookie" as your cookie name, it will be removed by browsers with Disable 3rd Party Cookies switched on - this includes all Safari users and many others who purposefully enable it.

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 seamlessly 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.

If you need a CORS Polyfill and you're here because of IE, give this XHook CORS polyfill a try, however, be mindful of the restrictions listed below.

FAQ / Troubleshooting

Q: But I love CORS

A: You shouldn't. You should use XDomain because:

  • IE uses a different API (XDomainRequest) for CORS, XDomain normalizes this silliness. XDomainRequest also has many restrictions:

    • Requests must be GET or POST
    • Requests must use the same protocol as the page http -> http
    • Requests only emit progress,timeout and error
    • Requests may only use the Content-Type header
  • The CORS spec is not as simple as it seems, XDomain allows you to use plain XHR instead.

  • On a RESTful JSON API server, CORS will generate superfluous traffic by sending a preflight OPTIONS request preceding various types of requests.

  • Not everyone is able to modify HTTP headers on the server, but most can upload a proxy.html file.

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

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

Q: XDomain is interfering with another library!

A: XDomain attempts to perfectly implement XMLHttpRequest2 so there should be no differences. If there is a difference, create an issue. Note however, one purposeful difference affects some libraries under IE. Many use the presence of 'withCredentials' in new XMLHttpRequest() to determine if the browser supports CORS.

The most notable library that does this is jQuery, so XHook purposefully defines withCredentials to trick jQuery into thinking the browser supports CORS, thereby allowing XDomain to function seamlessly in IE. However, this fix is detrimental to other libraries like: MixPanel, FB SDK, Intercom as they will incorrectly attempt CORS on domains which don't have a proxy.html. So, if you are using any of these libraries which implement their own CORS workarounds, you can do the following to manually disable defining withCredentials and manually reenable CORS on jQuery:

//fix trackers
xhook.addWithCredentials = false;
//fix jquery cors
jQuery.support.cors = true;

Note: In newer browsers xhook.addWithCredentials has no effect as they already support withCredentials.

Q: XDomain works for a few requests and then it stops.

A: Most likely, the slave iframe was removed - this is often due to libraries like Turbolinks

Q: In IE, I'm getting an Access Denied error

A: This is error occurs when IE attempts a CORS request. Read on.

Q: The browser is still sending CORS requests.

A: Double check your slaves configuration against the examples. If your slaves configuration is correct, double-check that you're including XDomain before window.XMLHttpRequest is referenced anywhere. The safest way to fix it is to include XDomain first, it has no dependencies, it only modifies window.XMLHttpRequest.

Q: The script is loads but the 'Quick Start' steps don't work

A: XDomain only searches the script tags for master and slave attributes if they have xdomain in the src. So, if you've renamed or embedded XDomain, you'll need to use the API in order to insert your masters and slaves.

Q: It's still not working!

A: Enable xdomain.debug = true; (or add a debug="true" attribute to the script tag) on both the master and the slave and copy the console.logs to a new issue. If possible, please provide a live example demonstrating your issue.

Change log

  • 0.8.2

    • Removed CoffeeScript
    • Restructured with ES6 and Common.js
    • Use parcel as bundler

Todo

  • Saucelabs testing is broken, need to swap to BrowserStack.

Contributing

  • npm install
  • Tab 1
    • npm run dev
  • Tab 2
    • npm i -g serve
    • serve -p 3000 .
    • open http://localhost:3000/example/local
  • npm run build
  • See dist/

Donate

BTC 1AxEWoz121JSC3rV8e9MkaN9GAc5Jxvs4

MIT License

Copyright © 2016 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.

Analytics

xdomain's People

Contributors

ajgagnon avatar brian-mann avatar briangonzalez avatar eligrey avatar jpillora avatar jpsirois avatar mkcom avatar mscdex avatar soncodi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xdomain's Issues

Feature: Add parent url as param to iframe src

Before considering this as a feature, I'm trying to find a way to know the current page that the iframe generated on.

In my API, I check for the HTTP_REFERER which will be the /proxy.html, but is there anyway to know whats the parent of the HTTP_REFERER?

So I hacked it to have the iframe src to be /proxy.html?parent=window.parent.location.href and so I can know the parent host of the iframe.

xdomain doesn't work in IE8 if "Enable native XMLHTTP support" disabled

Hi. It seems that xdomain doesn't work in IE8 if "Enable native XMLHTTP support" is disabled in the advanced preferences.

By disabling that, IE relies on MSXML.HttpRequest - I didn't see anything in the code that deals with that, the only reference to ActiveXObjects I found is in patchClass("ActiveXObject");

Does xdomain.js support that use case?

Thanks in advance.

xhook/xdomain support for XHR#abort()

I'm using XDomain here with success, so thanks for the work! I've contributed a couple of bugfixes to the projects in the past, so thanks for your attention on those.

I'm running into an issue that seems like it involves a more sophisticated fix. I'm working on it now/soon but wanted to bounce the general problem and approach off you to see if you had any thoughts.

Specifically, in XDomain xhr.abort() doesn't do anything. transiting is never set to true if the before hook exists (as it does in XDomain), so no XHR is aborted. This has presented a specific problem for us in our app since we call xhr.abort() in a cleanup process that includes dereferencing the xhr. That, combined with the way the EventEmitter works, makes it so that the final success and state change callbacks still get called, which produces a null reference way down the line in our app. We could patch it up at many levels in our app or at the surface level in XHook (for instance, making the facade's abort function remove the success hooks), but I'm interested in a deeper fix that actually implements abort. Due to the asynchronous nature of postMessage, it probably won't be perfect, but it feels more "right".

The approach I'm examining is to add a new window.xhook function (alongside before and after), for instance abort, that basically intercepts window.XMLHttpRequest.prototype.abort the way that before intercepts window.XMLHttpRequest.prototype.send. Then implement the abort method in XDomain to post some new message structure (send produces something like {"id":"000","msg":{...}}, so maybe something like {"id":"000","action":"abort"}). If I had setupReceiver on the proxy page include some dictionary of ongoing requests, we could just listen for that sort of message and abort accordingly. If that all sounds kosher to you, I'd be happy to put in the dev work to make it happen.

Success handler fired on aborted request with jQuery 2.x

When using xdomain and jQuery 2.x, when a long-running request is aborted (in this case, by navigating away from the page), the success handler passed to jQuery is executed, even though it should not be.

I verified this does not happen using jQuery 1.7.2.

Troubleshooting IE8/9

This is more a 'FYI' that maybe should be appended to the README.md

When you run xdomain in IE8/9 - you must properly declare the Doctype at the top of your HTML, else IE8/9 will run the page in quirks mode which breaks JSON compatibility for IE.

Whilst this manifests itself nicely, unfortunately IE9 then throws the error 'console not defined' in xdomain.min.js - removing the two references to console correctly pop's up the alert box that says 'Your browser does not support JSON'.

Android 4.1.2 Incompatible

I'll provide more details and a stacktrace when I can but ran into this today. Had to remove xdomain to get Droid 4.1.2 to work at all. (Jelly Bean native browser)

Actual referrer

Hi,

Can you tell me if there is a way to get the actual referrer, rather than it being the proxy URL?

Custom Headers being set before setRequestHeader is populated.

Hello,

I'm not sure if this is a problem with my implementation or a bug that's yet to be noticed. I'm using jQuery and Backbone, in case that matters. My problem is, I need custom headers for my CORS request to work (I send Accept, X-CSRF-Token and Authorization headers, all needed for the API to respond accordingly), but they are not being sent when using xdomain.

After much debugging, I found out xdomain IS receiving the headers, but the xhr.setRequestHeader() function seems to be called before the request headers are set.

Being a little more specific, I added two console logs. One right after this line, logging the userRequestHeaders object, the other one right after this other line, logging the same object. I then launched my console and I'm seeing the setValue function being called BEFORE the switch has been activated (and thus, populated with the custom headers). Here's a screenshot of firebug's output:

screen shot 2014-01-14 at 5 35

I saw the examples, and custom headers seem to be being sent just fine on them, so I apologise if this is an issue on my end (and if it is, would appreciate any direction as to where the error might be).

Thanks for your time!

Update bower and use a directory scheme that is.."friendly"

Ok..Seems like I am posting too many issues to this project =P

I am testing xdomain project using bower..Ok, but, I when use the version in dist/xdomain.js, the version used is very...old (v0.4), and the correct folder is in...dist/0.6/xdomain.js. If the expected version is in a folder related to a version, why use tag releases? It seems not very helpful..(tag releases is, but not the folder with the version =P)

Other thing: Seems like a new tag release is needed to bower correctly install the bugfix v0.6.1, here, its downloading the version v0.6, which is affected by the bug #39 and its not....good.

The solution for all this issue is at all very easy to do. But its good to register these things anyway..

Thanks and sorry for the amount of comments this night =) (and for the poor english, lol)

Using xdomain in conjunction with a MongoLab Instance

Hi Jaime,

I came across your xdomain project when googling for IE9 and angular CORS problems. What you've done with xdomain looks pretty neat and looks to solve the problem I am having with some IE9 users on a site that I am running (http://www.kentramblers.org.uk/EKWG/#/walks). The site is an angular application and makes calls to a backend MongoLab instance from within the javascript client. On the first call to the Mongolab instance (on https://api.mongolab.com), 'Error: Access is denied' appears in the IE console. Other browsers (Chrome, Firefox, IE 11 are fine).

There's something I don't understand in README.md with regard to the master/slave domains. If I want to make calls to the mongolab instance does this mean that https://api.mongolab.com is the slave or the master? I guess if it's either, then this solution wont work as I have no control over creating a proxy on that environment? Or is there still hope for me?

Any advice welcomed please!

Cheers, Nick Barrett

Allow use with any AJAX library

Though it'll remain jQuery by default, I could add hooks to allow it to be used with any library, e.g angular resource, zepto, superagent. I have a feeling it might get messy so I have a feeling the cleanest and most user friendly solution is to make multiple builds, one per library

This issue is for separating out jQuery, will then make more for other libraries which will use the same hooks as the "jQuery xdomain adapter"

Issue with X-Frame-Options ?

When loading up the script from my master domain (the one making AJAX requests), received the following error in the JS console:

Refused to display 'http://localhost:3000/proxy.html' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

Is this an issue with my server configuration?

XDomain v0.6 does not work on on IOS 5.1 and IOS 6 (verified on IPAD 1 and other devices)

v0.6 works on IOS 7 as verified,

v0.5 works on IOS 5.1, 6 and 7 but there is the file upload issue...

Error can be displayed on safari using the console.

----
Javascript: Error
undefined
SYNTAX_ERR: DOM Exception 12: An Invalid or illegal string was specified.
----

This is quite a blocking / urgent bug as it prevent xdomin to be used on these IOS versions.

Found this if it can help:

SYNTAX_ERR code 12
In invalid or illegal string has been specified; for example setting the selectorText property of a CSSStyleRule with an invalid CSS value.

Let us know if we can help / test: the fix is quite urgent for us ;-)

xdomain incompatibility with latest build of angular

Hey @jpillora, we have seen a strange case where GET request would return an empty body when using xdomai with the latest angular build from bower, as it seems that thy conflict in the way the response is set (xhr.response / xhr.responseText).

If you have a look the guys at angular actually did a change a file called httpBackend.js that works with the response body...

We're looking into it but I thought its worth mentioning...

Update Version in Source

At the head of the dist/0.6/xdomain.js and xdomain.min.js files, the version is still listed as 0.6.5, even though version 0.6.6 has been tagged.

Proper way to use XDomain together with XHook

Hi there,

XDomain is working perfectly to allow cross-origin AJAX requests.

I'd also like to use the built-in XHook functionality to stub out some requests to specific routes. This works fine when the url is local to the source, but not cross-domain. For example, using the following before_hook:

xhook.before(function(request, callback) {
  if (RegExp("^(.*)/change_password$").test(request.url)) {
    return callback({
      status: 200,
      statusText: "OK",
      text: ' {"message": "Password updated."} ',
      headers: {
        'Content-Type': "application/json; charset=utf-8"
      }
    });
  }
});

works fine if I perform an ajax request to /api/change_password, but not if I perform one to http://localhost:3000/api/change_password. It would appear that XHook is not grabbing requests that are going cross-domain. I could be doing something wrong though.

InvalidStateError

I have my webapp setup correctly according to the docs, but I get the following error when calling my slave:

Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. xdomain.min.js:3
a.(anonymous function).B.(anonymous function) xdomain.min.js:3
Response build.js:3463
(anonymous function) build.js:3607
Emitter.emit build.js:2982
xhr.onreadystatechange build.js:3936
v.trigger xdomain.min.js:3
v.set xdomain.min.js:3
v.deserialize xdomain.min.js:3
(anonymous function) xdomain.min.js:3
(anonymous function) xdomain.min.js:3
a.recieve xdomain.min.js:3
(anonymous function) xdomain.min.js:3

"Failed to parse url" error when fetching a relative url

When I fetch a relative url, I get these errors on master:
LOG: xdomain (http://blaise.local:8000): failed to parse url: /some/relative/url/

I would expect relative url's (protocol-relative, host-relative) to work. Maybe patch parseUrl to prepend the master's protocol if the protocol is unspecified, and return the master's origin if no hostname is specified?

Environment: Windows 7, IE9, Strict mode.

xdomain responses do not work well with recent Angular updates due to changes in httpBackend

We've recently discovered a serious IE8/IE9 defect between Angular 1.2.10+ and the xdomain library. Initially I thought it to be an Angular defect and reported it as a bug. After further investigation though I realized that the cause of the issue was the interplay between Angular's $httpBackend (line 94), the xdomain's initialization of facade.

Angular checks for response vs responseText like this:

response = ('response' in xhr) ? xhr.response : xhr.responseText;

However, the xdomain lib always initializes a response attribute (even if it's null for IE) and so this causes any values in responseText data to be overlooked.

Fortunately the fix for this is a simple 2-parter.

  1. Line 326: do not initialize response to null.
facade.response = null;
  1. Change writeBody to be more like this:
  writeBody = function() {
    if ( response.hasOwnProperty('text') ) {
      facade.responseText = response.text;
    } else if ( response.hasOwnProperty('xml') ) {
      facade.responseXML = response.xml;
    } else {
      facade.response = response.data || null;
    }
  };

Need refresh before working in IE/9

I've added this to my project and it seems to work, except that I need to refresh before any requests succeed. I'm not seeing any errors in the console. On the front end I have:

<script src="http://jpillora.com/xdomain/dist/0.5/xdomain.min.js" slave="http://my-back-end.com/proxy.html"></script>

And in the backend:

<!DOCTYPE HTML>
<script src="http://jpillora.com/xdomain/dist/0.5/xdomain.min.js" master="http://my-front-end.herokuapp.com"></script>

Any ideas?

Does xdomain support uploads and FormData?

Hi Jamie,
I'm trying to upload files under xdomain but seems xdomain is not handling the file.
In a first place I thought was an issue with another XHR see this issue.

But then I realize the issue is the same even without the XHR hack.

I saw xHook 1.1 is handling upload stuff but xDomain 0.5 is still not using it!

Then I saw your 0.6 version of xDomain that seems to be intended to solve this issues.

I'm wrong?

  • is there a way to handle files upload now (with 0.5)?
  • if not, how can we help you in the 0.6 version of xDomain?

we really need it so please tell me how can I help to put 0.6 out!

Thanks for the library and for helping

Does not work in current Firefox

In FF 23.0.1 the JSON data never appears on the test page. The only error I see in the console seems unrelated: The character encoding of the HTML document was not declared...

In Chrome the page works as expected.

Not working on OS X Mavericks

Hello, I have a strange bug when I run the page, the console say:

Uncaught Timeout connecting to iframe: http://s3.amazonaws.com xdomain.js:598
Frame.readyCheck xdomain.js:598
(anonymous function)

I hope it will help you to fix this bug

Better scoping of events.

I have an application that uses postMessage directly. This causes errors with the xdomain Ajax requests. In particular, I'm sending objects rather than strings, so the JSON.parse throws.

Allow use with any AJAX library

Though it'll remain jQuery by default, I could add hooks to allow it to be used with any library, e.g angular resource, zepto, superagent. I have a feeling it might get messy so I have a feeling the cleanest and most user friendly solution is to make multiple builds, one per library

This issue is for separating out jQuery, will then make more for other libraries which will use the same hooks as the "jQuery xdomain adapter"

Loses xhr onprogress events

xdomain does not proxy(?) the XMLHttpRequest progress events. None of the following work.

    var xhr = new XMLHttpRequest();

    xhr.upload.onprogress = function (e) {
        ...
    };

    xhr.progress = function (e) {
        ...
    };

    xhr.addEventListener('progress', function (e) {
        ...
    });

Crashes browser tab when under heavy load.

Apologies for this being a vague issue report, I am trying to nail down the exact cause and test case. I have a large-ish single page app, and at times (usually after the source has been rebuilt and the browser is loading fresh js files) when xdomain is making several request it will cause the browser tab to hang, in a memory leak sort of fashion. The tab never recovers and has to be closed.
I have noticed this in latest Chrome & Chrome Canary on Mac OSX 10.8.4

Problems on saucelabs

Hey @jpillora,

just as a warning / memo: we are trying to run our automated tests on saucelabs but it seems that xdomain makes them fail. No logs, the browser hangs. Removing xdomain solved the issue.

Do you have any hint / advice?

(@AdamQuadmon can provide more insights!)

Document when a CORS polyfill is required.

It's not obvious if and when a CORS polyfill is required. It might be good to note which browsers do not support CORS and make it more clear if and how this polyfill differs from the behaviour that a standard "Access-Control-Allow-Origin: *" header allows.

Problem loading views in angularjs

I'm not sure how much this project intends to support AngularJS, but I have found that, while attempting to use routes/views, the data does not load.

Tag releases

Hello,

We can't install latest versions with bower because they doesn't have any tag:

screenshot at 2014-02-26 15 43 38

Please just push tags :-) .

Thank you.

Does xdomain detect CORS support first?

Hello,

Do you detect CORS support before rewriting window.XMLHttpRequest?
For example, IE9 gets the benefits of this, but IE10 which supports CORS gets the original XMLHttpRequest object?

[enhancement] Add missing bower.json.

Hey, maintainer(s) of jpillora/xdomain!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library jpillora/xdomain is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "jpillora/xdomain",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

xdomain breaks mixpanel JS client library when loaded later in IE 8/IE 9 ("Access is Denied")

From an implementation perspective, it may be an xhook issue, but it manifests in xdomain. In particular, the facade object that xhook's replaced XMLHttpRequest constructor returns includes the withCredentials property. This "breaks" mixpanel, which uses the presence of withCredentials (namely, something like 'withCredentials' in (new XMLHttpRequest)) to determine whether to use XHRs instead of image beacons.

The result is that mixpanel wrongly infers based on the presence of the withCredentials property that the user agent supports CORS XHRs, and the subsequent XHR to mixpanel breaks things ('Access is Denied' on XHR#open).

I'll whip up a working PoC later today. Just wanted to set up a placeholder issue with the report so I can link to something in my hack fix.

Is it possible to use this without effecting all XHRs from the page?

I am working on a third-party library that could benefit fro musing xdomain, but I can't presume to effect the XHR behavior of the pages hosting my library.

The use case for me would be to be able to use xdomain explicitly, rather than use it as a behind the scenes default. Is that possible?

Thanks for your attention!

Getting Access Denied Error at line 3... for all CSS files with AngularJS 1.2.8

I've tried placing the XDomain script in various places with no luck. I also just udpated it to the latest. What is really strange is that my very first API call in the header seems to actually work and pull in data, but then the rest of the page fails and repeatedly gets stuck on the XDomain.js file.
I am on https and all of the cdn script and css references use relative paths (like src="//cdnjs.cloudflare.com/scripts..")
When I check the IE8 web dev console, and 'watch' the s.url param where I'm getting the 'Access Denied' message, it appears to be all of the CSS files.
Also, I am using .Net MVC for the backend with HTML,JS code in both _Layout.html and Index.html, and then all of the other content is pulled in from Angular and partial views. I tried adding the XDomain script at the very top in the head section of _Layout.html, but then thought that maybe that was why it was trying to 'get' the CSS files through XDomain so I moved it to the Index.html file right above the body content where the ng-app is defined (still above Angular and all of the other JS at the bottom). But I am still getting the same Access Denied errors and the page doesn't load all... it gets 'hung'.

Any thoughts?

Improve Documentation

I'm sure I'm just being a newb, but could we see an example of the HTML required on the master node to multiple slaves. Each of my attempts so far has just resulted in access denied errors. Putting it in the script tag (only 1 slave) worked first time.

Thanks in advance!
Ben

P.S For example

     <!--[if lte IE 10]>
     <script src="http://jpillora.com/xdomain/dist/0.5/xdomain.min.js"></script>
     <script>
         xdomain({
             slaves: {
                 'http://dev.api.example.com/proxy.html': 'proxy.html',
                 'http://dev.api.example2.com/proxy.html': 'proxy.html',
             }
         });
     </script>
     <![endif]-->

Add Api function to allow for config

Based on this api suggestion for xhook and also #48

Config method options:

  • set 'withCredentials: true'
  • default interference handling (on/off) default being true
  • set default handling for withCredentials requests (#12)
  • set an interference exceptions option to override the current interference setting
  • implement and/or to prevent conflicting directives

Allow for:

<script>
   xdomain.config({
        interfere:true, //this is the default setting,
        withCredentials, //represents the default, can be turned around here globally, or in configs below individually
        //options in this section will override the interfere setting (true by
        exceptions: { 
                  // array of objects, each representing a group of settings from the config list below
                 x_or: [  ], 
                 x_and: [  ]
          }
     });
 </script>

Or/And config settings (maybe use any/all instead?)

  • user-agent string/array
  • content-type string
  • destination host string/array
  • methods string/array
  • paths string/array (paths from origin that overide the current interfere setting)

Question regarding 'FAQ' section

So after looking over this project (and I like the ideas as it is simple to implement), I feel there is a small problem with your protocol description of the CORS protocol (or rather current working draft).

On RESTful JSON API server, CORS will send a preflight OPTIONS request on every request except GET, generating superfluous traffic.

However, according to the latest working draft (section on methods defined as 'simple')

It gets slightly more complicated if the resource author wants to be able to handle cross-origin requests using methods other than simple methods. In that case the author needs to reply to a preflight request that uses the OPTIONS method and then needs to handle the actual request that uses the desired method (DELETE in this example) and give an appropriate response. The response to the preflight request could have the following headers specified:

Which would be 'GET, HEAD & POST' methods that do not generate superfluous traffic where the RESTful JSON API server would need to respond to ORIGIN preflight requests on PUT & DELETE requests only.

Does this require a pull request to remedy?

dist/0.5 - xdomain throws error - Uncaught InvalidStateError

Using <!DOCTYPE HTML> in Chrome, latest version, 30.0.1599.69. Using the dist/0.5 files.
Of course this also makes everything fail in IE.

However, the other files in dist (not in 0.5 folder) do not throw errors, v0.4.3. Unfortunately those files do not work in IE 8/9 (again using standard <!DOCTYPE HTML> as mentioned).

Contrary to the README, the warning about "...missing JSON" still occurs in IE 8/9 with v0.4.3 flavor regardless of the doctype specification.

Any pointers or help?

screen shot 2013-10-08 at 9 36 01 am
screen shot 2013-10-08 at 9 35 33 am

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.