Search code examples
cross-domainjsonpxmlhttprequest

How do browsers assess the origin domain for XMLHttpRequest?


I thought that the origin domain for XMLHttpRequest was the domain that loaded the javascript that is using it.

For instance, It thought that if on a page http://mydomain1.com/ I have:

<script src="http://mydomain2.com/script.js" />

script.js can interact with mydomain2.com via XHR. This was, I thought, one of the nice things about jsonp.

I am seeing a bit of evidence in some testing that even though JS loads from mydomain2.com, XHR's origin is still mydomain1.com. Have I just been way off base all this time?


Solution

  • It is the domain of the page (possibly in a frame) which executes the JavaScript.

    If it were from the domain with which the JavaScript was loaded, what would happen for all the people using jQuery.ajax after loading jQuery from a CDN (such as this)?

    JSONP doesn't allow acting as another domain, but rather it allows injecting from another domain. The source URI of the script element is not restricted to the same domain origin restriction as XHR: in this manner JSONP can be used to freely send data (in the URI) and execute the returned JavaScript (not JSON) directly in the context of the current page.

    Including script tags from remote sites allows the remote sites to inject any content into a website. If the remote sites have vulnerabilities that allow JavaScript injection, the original site can also be affected.

    Happy coding.