Friday, February 25, 2011

JavaScript Cross Domain Call

Let's create a Asp.net Empty Web application called JavaScriptCrossDomainTopic. Let's add a new HTML page called "MyTestPage". Let's include the Jquery library, and write some code like:

< script type="text/javascript">
$(document).ready(function () {
$.get("http://google.com");
});
< /script>

in the body tags.

see the following picture:



By defaut internet browser security setting, when we browse our test page, there will pop up a window. saying :
"The page is accessing information that is not under its control. This poses a security risk. Do you want to continue?"



We can get rid of this pop up by do the browser security setting. But what causes this pop up.

Let's write some code to create XMLHttpRequest object and use it to request the url.

function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch (e) { }
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
alert("XMLHttpRequest not supported");
return null;
}

< script type="text/javascript">
$(document).ready(function ()
var xhReq = createXMLHttpRequest();
xhReq.open("get", "http://google.com", true);
xhReq.send(null); });
< /script>

This also has the security pop up. This is so called "Same Origin Policy". Please find materials about this ourselves.

We can use Jquery, $.get(), $.post() or ajax call ($.ajax({url:...}) , all will have the cross domain issure. The reason is all these methods are encentially use the XmlHttpObject to call the url.

As I want my application don't have this anoying pop up, we need to by pass the client-side cross domain restriction.

Here is an important princeple:

The same-origin policy doesn't prevent adding scripts/Images/or other Elements dynamically in the page from a different domain as long as the script doesn't try to load document from a different domain.

so we wrote code like the following to call a cross domain url in client side:

var script=document.createElement('script'); //or var myImage=new Image();

script.src="http://...."; //or myImage.src="";
//or var url="";script.setAttribute('src', url);

document.body.appendChild(script); //or document.body.append(myImage);

See the following picture:



and We browse our test page, we will find there is no pop up again. We bypass the cross domain restriction!

In many situations we need to use javaScript to call a Web/WCF service, for example we create a REST WCF service in the previous article. If a Web/WCF service has Json response support.

There is a technique called JsonP.

$.getJSON("http://www.anotherdomain.svc/MyRESTService/GetProduct?id=3&name=apple&price=1.25&callback=?", function(data) {
//do something here.
});

There will not have cross domain issue as well. By my understanding, JsonP also use the our mechnism above to load to the same domain an Element which has src attribute set to the Json service.

No comments: