Description of steps
Write "callback" function on my custom page in my domain (called "MyCallbackCallback", for the sake of argument)
Open new window (from different domain) and pass function name in as part of query string
New window does what it needs to do then tries to access "MyCallback" from my custom page
This obviously won't work and will return "Access denied" error.
If there was a way of "allowing" the 3rd-party domain access to my domain that would solve the issue, of course. Is there such a thing? I know there is in Action Script, but JavaScript??
NB - I am aware that setting "document.domain" on both pages, (or creating both pages in the same domain) will solve the issue, but I almost certainly won't have this option.
If the answer is "you can't" that's fine - I just need to know. I have spent many hours searching and can't find a simple answer (there may not be one!)
Ta, Rob
It’s not exactly clear from your question, but if you’re trying to use CORS, the server you’re requesting data from should add an Access-Control-Allow-Origin HTTP header, like so:
Access-Control-Allow-Origin: http://example.org/
Or, if it’s a public resource:
Access-Control-Allow-Origin: *
Older browsers don’t support CORS. If you need a fully cross-browser-compatible solution, use JSONP.
Have a look at Cross-Domain AJAX requests:
https://developer.mozilla.org/En/HTTP_Access_Control
http://msdn.microsoft.com/en-us/library/dd573303%28v=vs.85%29.aspx
JSONP is the only method compatible with older browsers though.
If you want cross-domain communication without serverside proxies (perfect for the kind of RPC that you are describing) then take a look at easyXDM.
You can find multiple demos here.
Related
I am looking for ways to allow cross-domain access using $.getJSON. I came across solutions which suggest that using CORS is the solution to this problem. But most of the solutions have a general ajax format.
I cannot use JSONP since I get data from a server which I do not have access. Is there a way to modify this code using $.getJSON to get the data?
$.getJSON(jsonURL, function(res){
console.log(JSON.stringify(res));
});
Or do I have to use ajax format for CORS?
Server which I do not have access
I think, this will break your neck.
You need some kind of access to the server or contact someone who has. At least you have to adjust the HTTP-Header to enter your domain Access-Control-Allow-Origin is the keyword.
Have a look at MDN
If you have access to set the HTTP Response Headers for the page that loads your JS scripts, then YES you can use CORS to send cross-domain requests. However, this is not supported in older browsers.
You need to set the Access-Control-Allow-Origin header, e.g.
Access-Control-Allow-Origin: *
Or
Access-Control-Allow-Origin: http://host-of-other-site.com
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
Imagine, that you have two domains and you want them to interact through a Javascript mechanism.
So, what I've done so far is host two servers on different ports on my local machine. It seems that the request is being sent from one server to another, only it doesn't seem to return any data.
What do you think the problem is ? How can I solve it ?
P.S. Code examples would be greatly appreciated. Thank you.
I don't know about django, but the other domain must support CORS (see Wikipedia and the w3 spec).
Basically, the remote server must support the Access-Control-Allow-Origin header. Usually I just have my server set the header value to * to allow all origins to access data.
You might need to find more specific documentation for your particular webserver. You might also want to watch the conversation between servers using wireshark. It's a great little utility for finding out what's really happening with your HTTP requests/responses...
You need to add an extra header to host 2 to allow host 1. This site will help you http://enable-cors.org/
JSONP is about to solve cross domain issues:
http://en.wikipedia.org/wiki/JSONP
jQuery has good functionality to support JSONP,
(just some googled link of this topic)
http://sangers.nu/blog/tech/20090129-jsonp-with-jquery
EDIT:
JSONP could look a little weird than at first sight :) basically should support JSONP notation (call callback method, if it is provided). So, it checks if 'callback' method is provided and instead of returning results like
{ some: 12 }
It does,
callback( { some: 12 } )
Here is my blog post on that:
http://www.beletsky.net/2010/07/json-jsonp-and-same-origin-policy-issue.html
jsonp is your option infact I used a django snippet available here
http://djangosnippets.org/snippets/2208/
For example there are lalalalaal.com that do NOT exist. Is there any way using JavaScript (possibly with jQuery) to check is given link really exist?
There has to be a server involved because of the Same Origin Policy — but it doesn't necessarily follow that it has to be your server. :-)
You can use a third-party service such as Yahoo to do the proxying for you as discussed here: "Using YQL as a proxy for cross-domain Ajax". That shows how to use jQuery to query YQL's JSON-P and JSON-P-X interfaces for another domain's content.
It's not complicated, from the article:
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
container.html(data.results[0]);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
}
);
There isn't, the response from another domain will always be null (the same origin policy applies here). You'd have to contact your own domain and have it check server-side if the site actually exists...but JavaScript alone can't do this.
No, there isn't.
In order to find out if a URL exists, you have to make a request to it and see if you get a response. The same origin policy prevents JavaScript, running in a browser under normal security conditions, from reading responses from different hosts.
I don't think you can, for security reasons (same domain policy).
Use AnyOrigin or the FOSS clone I made of it, WhateverOrigin.
I'd like to offer a way to my users to promote my website, blog etc. on their website.
I can make a banner, logo whatever that they can embed to their site, but I'd like to offer dynamic content, like "the 5 newest entry's title from my blog".
The problem is the same origin policy. I know there is a solution (and I use it): they embed a simple div and a JavaScript file. The JS makes an XmlHttpRequest to my server and gets the data as JSONP, parses the data and inserts into the div.
But is it the only way? Isn't there a better way I could do this?
On the Internet there are tons of widget (or whatever, I don't know how they call...) that gain the data from another domain. How they do that?
A common theme of many of the solutions, instead, is getting JavaScript to call a proxy program (either on the client or the server) which, in turn, calls the web service for you.
The output can be written to the response stream and then is available, via the normal channels, such as the responseText and responseXML properties of XMLHttpRequest.
you can find more solution here :
http://developer.yahoo.com/javascript/howto-proxy.html
or here :
http://www.simple-talk.com/dotnet/asp.net/calling-cross-domain-web-services-in-ajax/
CORS is a different way than JSONP.
Plain AJAX. All your server has to do is to set a specific header: Access-Control-Allow-Origin
More here: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
If you go the JSONP route, you will implicitly ask your users to trust you, as they will give you full access to the resources of their page (content, cookies,...). If they know that they main complain.
While if you go the iframe route there is no problems.One famous example today of embeddable content by iframe is the Like button of facebook.
And making that server side with a proxy or other methods would be much more complex, as there are plenty of environments out there. I don't know other ways.
You can also set the HTTP Access-Control headers in the server side. This way you're basically controlling from the server side on whether the client who has fired the XMLHttpRequest is allowed to process the response. Any recent (and decent) webbrowser will take action accordingly.
Here's a PHP-targeted example how to set the headers accordingly.
header('Access-Control-Allow-Origin: *'); // Everone may process the response.
header('Access-Control-Max-Age: 604800'); // Client may cache this for one week.
header('Access-Control-Allow-Methods: GET, POST'); // Allowed request methods.
The key is Access-Control-Allow-Origin: *. This informs the client that requests originating from * (in fact, everywhere) is allowed to process the response. If you set it to for example Access-Control-Allow-Origin: http://example.com, then the webbrowser may only process the response when the initial page is been served from the mentioned domain.
See also:
MDC - HTTP Access Control
Let's say I have the main page loaded from http://www.example.com/index.html. On that page there is js code that makes an ajax request to http://n1.example.com//echo?message=hello. When the response is received a div on the main page is updated with the response body.
Will that work on all popular browsers?
Edit:
The obvious solution is to put a proxy in front of www.example.com and n1.example.com and set it so that every request going to a subresource of http://www.example.com/n1 gets proxied to http://n1.example.com/.
Cross domain is entirely a different subject. But cross sub-domain is relatively easy. All you need to do is to set the document.domain to be same in both the parent page and the iframe page.
document.domain = "yourdomain.com"
More info here
Note: this technique will only let you interact with iframes from parents of your domain. It does not alter the Origin sent by XMLHttpRequest.
All modern browsers support CORS and henceforth we should leverage this addition.
It works on simple handshaking technique were the 2 domains communicating trust each other by way of HTTP headers sent/received. This was long awaited as same origin policy was necessary to avoid XSS and other malicious attempts.
To initiate a cross-origin request, a browser sends the request with an Origin HTTP header. The value of this header is the site that served the page. For example, suppose a page on http://www.example-social-network.com attempts to access a user's data in online-personal-calendar.com. If the user's browser implements CORS, the following request header would be sent:
Origin: http://www.example-social-network.com
If online-personal-calendar.com allows the request, it sends an Access-Control-Allow-Origin header in its response. The value of the header indicates what origin sites are allowed. For example, a response to the previous request would contain the following:
Access-Control-Allow-Origin: http://www.example-social-network.com
If the server does not allow the cross-origin request, the browser will deliver an error to example-social-network.com page instead of the online-personal-calendar.com response.
To allow access to all pages, a server can send the following response header:
Access-Control-Allow-Origin: *
However, this might not be appropriate for situations in which security is a concern.
Very well explained here in below wiki page.
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Another solution that may or may not work for you is to dynamically insert/remove script tags in your DOM that point to the target domain. This will work if the target returns json and supports a callback.
Function to handle the result:
<script type="text/javascript">
function foo(result) {
alert( result );
}
</script>
Instead of doing an AJAX request you would dynamically insert something like this:
<script type="text/javascript" src="http://n1.example.com/echo?callback=foo"></script>
Another workaround, is to direct the ajax request to a php (for example) page on your domain, and in that page make a cURL request to the subdomain.
The simplest solution I found was to create a php on your subdomain and include your original function file within it using a full path.
Example:
www.domain.com/ajax/this_is_where_the_php_is_called.php
Subdomain:
sub.domain.com
Create:
sub.domain.com/I_need_the_function.php
Inside I_need_the_function.php just use an include:
include_once("/server/path/public_html/ajax/this_is_where_the_php_is_called.php");
Now call sub.domain.com/I_need_the_function.php from your javascript.
var sub="";
switch(window.location.hostname)
{
case "www.domain.com":
sub = "/ajax/this_is_where_the_php_is_called.php";
break;
case "domain.com":
sub = "";
break;
default: ///your subdomain (or add more "case" 's)
sub = "/I_need_the_function.php";
}
xmlHttp.open("GET",sub,true);
The example is as simple as I can make it. You may want to use better formatted paths.
I hope this helps some one. Nothing messy here - and you are calling the original file, so any edits will apply to all functions.
New idea: if you want cross subdomain (www.domain.com and sub.domain.com) and you are working on apache. things can get a lot easier. if a subdomain actually is a subdirectory in public_html (sub.domain.com = www.domain.com/sub/. so if you have ajax.domain.com/?request=subject...you can do something like this: www.domain.com/ajax/?request=subject
works like a charm for me, and no stupid hacks, proxies or difficult things to do for just a few Ajax requests!
I wrote a solution for cross sub domain and its been working for my applications. I used iframe and setting document.domain="domain.com" on both sides. You can find my solution at :
https://github.com/emphaticsunshine/Cross-sub-domain-solution