I'm trying to create a javascript plugin which needs the ability to send and receive data from another domain.
Conceptually, the plugin is simple:
The users installs a piece of javascript code
The code communicates with central server (on another domain), sends some info about the user's site (a form of query) and get's some info back
The server domain would be fully under my control , but as you can see, end-users should be able to use the plugin just by installing a piece of javascript code.
Is this possible and if yes, what would be the simplest form of implementation?
Thank you!
You basic problem will be circumventing the same origin policy of JavaScript (Wikipedia). Basically you have two options, if you want to use only JavaScript on the client side:
CORS (cross-origin resource sharing): Here you enable the sharing on your domain and the JavaScript on the user's side will be able to interact with any data as if it was on their own server, thus you have no problems with the same origin policy. You can do AJAX request in the same way as if interacting with your own server. For details on how to activate this on your server environment see here. Note however, that this is not supported by older browsers see caniuse.com for details.
JSONP: All requests use the JSONP syntax. Wikipedia on the topic
Related
Given the simplicity of writing a server side proxy that fetches data across domains, I'm at a loss as to what the initial intention was in preventing client side AJAX from making calls across domains. I'm not asking for speculation, I'm looking for documentation from the language designers (or people close to them) for what they thought they were doing, other than simply creating a mild inconvenience for developers.
TIA
It's to prevent that a browser acts as a reverse proxy. Suppose you are browsing http://www.evil.com from a PC at your office, and suppose that in that office exists an intranet with sensitive information at http://intranet.company.com which is only accessible from the local network.
If the cross domain policy wouldn't exists, www.evil.com could made ajax requests to http://intranet.company.com, using your browser as a reverse proxy, and send that information to www.evil.com with another Ajax request.
This one of the reasons of the restriction I guess.
If you're the author for myblog.com and you make an XHR to facebook.com, should the request send your facebook cookie credentials? No, that would mean that you could request users' private facebook information from your blog.
If you create a proxy service to do it, your proxy can't access the facebook cookies.
You may also be questioning why JSONP is OK. The reason is that you're loading a script you didn't write, so unless facebook's script decides to send you the information from their JS code, you won't have access to it
The most important reason for this limit is a security concern: should JSON request make browser serve and accept cookies or security credentials with request to another domain? It is not a concern with server-side proxy, because it don't have direct access to client environment. There was a proposal for safe sanitized JSON-specific request methods, but it wasn't implemented anywhere yet.
The difference between direct access and a proxy are cookies and other security relevant identification/verification information which are absolutely restricted to one origin.
With those, your browser can access sensitive data. Your proxy won't, as it does not know the user's login data.
Therefore, the proxy is only applicable to public data; as is CORS.
I know you are asking for experts' answers, I'm just a neophyte, and this is my opinion to why the server side proxy is not a proper final solution:
Building a server side proxy is not as easy as not build it at all.
Not always is possible like in a Third Party JS widget. You are not gonna ask all your publisher to declare a DNS register for integrate your widget. And modify the document.domain of his pages with the colateral issues.
As I read in the book Third Party Javascript "it requires loading an intermediary tunnel file before it can make cross-domain requests". At least you put JSONP in the game with more tricky juggling.
Not supported by IE8, also from the above book: "IE8 has a rather odd bug that prevents a top-level domain from communicating with its subdomain even when they both opt into a common domain namespace".
There are several security matters as people have explained in other answers, even more than them, you can check the chapter 4.3.2 Message exchange using subdomain proxies of the above book.
And the most important for me:
It is a hack.. like the JSONP solution, it's time for an standard, reliable, secure, clean and confortable solution.
But, after re-read your question, I think I still didn't answer it, so Why this AJAX security?, again I think, the answer is:
Because you don't want any web page you visit to be able to make calls from your desktop to any computer or server into your office's intranet
I need to provide a functionality similar to "Share with Facebook" for my social networking site. Facebook uses nested iframes and also xd_receiver concepts. I want to write a JavaScript API(JS file hosted on my domain), which can be used by different sites to call my web server APIs in order to share, post or recommend on my social networking site. I have a few questions -
Even though I provide the JS API, and diff sites load the JS file using the source, if any API call is made, it will again be a cross domain call(If I am comprehending correctly) and will be rejected on the server?
How to overcome such situation?
Is there any other better mechanism to implement this functionality?
Please suggest so that I can proceed with the implementation.
I think the default way is to use jsonp to get around cross domain limitation. http://en.wikipedia.org/wiki/JSONP. It might require a change in your api though. A user requests your api through the src of a script tag passing in a function callback. Your api would return pass your json response to the function specified.
Do you know why they use iframes and not simple get requests with JSONP/Images/scripts?
The answer is security. I cannot write a script that clicks their button which will automatically "like" the page.
Using plain old JavaScript with a JSONP will allow the developer to automatically click the button. Do you want that to happen?
The requests are made by the browser and not from the JS file, so, your requests will be cross-domain every time they did from another domain site.
Your server will only reject cross-domain requests if you implement a referrer validation.
And you can use JSONP if your API needs custom contents from your site...
To allow cross domain requests, you need to set the following Header in your HTTP Response:
Access-Control-Allow-Origin: *
The implementation will vary depending on the back-end you are using.
If the host in the Origin header of the request is anything but the host of the request, the response must include the listed Origin in the Access-Control-Allow-Origin header. Setting this header to * will allow all origins.
For very specific information on cross origin resource sharing see http://www.w3.org/TR/cors/. If you're not big on reading w3c documents, check out MDN's primer.
Note: Internet Explorer does its own thing with regards to cross domain requests. This answer is a good start if you have issues with IE.
I am writing an HTML5 application that is gathering data from a few different sources using JSONP. Anything I'm doing with a GET works perfectly. I'm now trying to POST data, and I've run into an interesting snag. I need to POST data from my application to another, where my application is running from a local machine. I am trying to write a cross-platform capable mobile application (think Pulse/Flipboard), so the code will always be running from a local source. My thought process was as follows:
Use JSONP - JSONP does not allow for posting, it just doesn't work that way (Post data to JsonP)
Rely on CORS - Since the request is coming from a local source using file://, the origin header is null. This causes the request to fail (XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin)
Use another server to bounce the request off of - this would be expensive
All of the browsers I'm targeting are webkit based (iPad, Playbook, Android), so I'm wondering if there are any creaks in the same origin policy code that I can sneak through? Maybe something using iframe or postMessage?
As it would turn out, the easiest way to do this is to post to the target url inside of an iframe. Same origin policy on most browsers allows you to perform an HTTP POST from one domain to another unrelated domain. I solved the problem by adding an iframe to my page, initially set to a local bootstrapping page. Since that page was loaded from the same domain, I am able to control it via script. I used that to post the form to my target site, and polled the results to determine if my call was successful. It's not elegant, but it works.
This Javascript library can almost certainly help you:
http://easyxdm.net/
easyXDM is a Javascript library that
enables you as a developer to easily
work around the limitation set in
place by the Same Origin Policy, in
turn making it easy to communicate and
expose javascript API’s across domain
boundaries.
..
At the core easyXDM provides a
transport stack capable of passing
string based messages between two
windows, a consumer (the main
document) and a provider (a document
included using an iframe). It does
this by using one of several available
techniques, always selecting the most
efficient one for the current browser.
For all implementations the transport
stack offers bi-directionality,
reliability, queueing and
sender-verification.
using JavaScript, it is much needed to get some pages from the web using without actually moving from the current page and hidden from the user's eyes.
To request a web page without showing it to the user, it is easy to use XMLHttpRequest but it has its own limitations most importantly it does not retrieve cross-domain pages very well. For security reasons the browsers (Mozilla FireFox 3.6+ in my case) retrieve a header from the target site and if the referrer's location is allowed access in that header, only then will the browser continue getting the target web page and JavaScript can only then parse the retrieved info.
This causes the XMLHttpRequest to work with some pages and not work with others if you are trying to access cross-domain pages. Of course it works well if you need to retrieve the information from the same location as the referrer page where the XMLHttpRequest is located.
This is a big problem, when security is not really no 1 priority. For example, imagine writing a script for retrieving live data from a statistics-producing web site or imagine a bot that needs to retrieve data from an online gaming web-site.
Now, how can JavaScript be used to get pages from other domains (cross-domain reference)?
I thought maybe we could find a plug-in that does the job (of course after installation upon user's permission) and then use its properties by JS and eliminate the need for XMLHttpRequest. Do you know any such plug-in or another roundabout for this problem? (ie get cross-domain data by JS without XMLHttpRequest) of course we cannot use XMLHttpRequest as we don't have any control over the target page headers and we obviously want to hide the whole process from the user
You’ll find that it’s the priority that the target site puts on their own security that is most important. If they're unconcerned about JavaScript on other sites accessing their site, they can set the HTTP Access Control headers for cross-domain XMLHTTPRequest, provide a crossdomain.xml file for Flash, provide a JSONP API, or provide some hooks for iframe monitoring.
The second solution is to make the requests to a server on your domain which proxies the request to the target site. In certain circumstances you may be able to use a third party server which supports cross-domain or JSONP requests, like Yahoo! Pipes.
If neither of these is feasible, you'll need to convince the user to allow you to run your own code on their PC. This could be via a signed Java applet which requests special permissions, or your own custom browser plugins or extensions.
There are several ways including using JSONP with XMLHttpRequest, using Flash and using iframes.
Here is some information on this subject. http://snook.ca/archives/javascript/cross_domain_aj
I'm wondering if anyone knows a javascript library where I could remotely login to a site, then browse pages upon logging in.
This is very easy with php's curl but I'm wondering if there is a javascript equivalent where I can execute multiple remote url's under a single http session.
Basically what I'm looking to do is post a username/password to one of my sites and then immediately post some other commands to a different url (same remote domain) using the authenticated session.
I haven't come across anything like this yet so I'm wondering if anyone can point me in the direction (if it's even possible). Can definitely be HTML5.
Due to same origin policy restrictions in browsers this is not possible using javascript. You need a server side script that will act as a bridge between your site and the remote sites. Then talk to this local script using AJAX.
There are some techniques available to bypass the same origin policy:
If you don't need to read the response of your POST calls, you can create a FORM by javascript with an action to any url (not limited to the same origin policy) like in this question: How do I send a cross-domain POST request via JavaScript?
But this means you rely only on session cookies for the security, this is open for XSS attacks.
As you own the other domain site, you could develop a small service that returns a JSON with the data you need, and use the JSONP technique, eg:
<script src="http://otherdomain/curl?url=page.html&callback=cb">
</script>
May be you could signin before using the POST technique above and sending a secret token that you reuse in the url to improve the security.
And finally there is a way to act/read on other pages using a bookmarklet.The idea is to inject in the other domain's page a script that can run with all the privileges, and send back information to your domain.
But this requires a manual action (click a link or a browser bookmark)