views:

124

answers:

2

I'm trying to write some Javascript that shows data based on an HTTP GET request to a server on a different domain. From what I've read, this is made tricky due to the SOP (Same Origin Policy).

I'm curious how snap.com "Snap Shots" (webpage previews) work. Here is an example page: http://premshree.livejournal.com/66129.html

Could someone explain how this is possible? To enable the snap.com "Snap Shots" all you have to do is add some Javascrpt to your header. It seems like the example webpage is disobeying SOP.

+1  A: 

The "Snap Shots" JavaScript is hosted on snap.com, therefore it has access to all things snap.com i.e. the page previews, as it does in fact obey the Same Origin Policy. It would not, however, be able to make any calls to any pages on livejournal.com.

Hope this helps.

Ian Oxley
+1  A: 

Following Ian's answer, you can get AJAX to cross the domain barrier presented by SOP using JSONP. What is JSONP? It is the same JSON object that we all know and love, but it is wrapped with a function: JSON:

{
  prop1: "a",
  prop2: 7
}

JSONP:

myfunction(
{
  prop1: "a",
  prop2: 7
});
As you can see, the JSON object is passed as a parameter to the myfunction function. So if you were to link to a script resource that is hosted on a different domain using a simple script tag, and that resource returned JSONP data, then you could simply define a function myfunction which accepts a JSON object and then do something with it. JQuery supports JSONP Ajax calls using the getJSON method. Rather than making an AJAX call, jQuery inserts a script tag pointing to the URL from which you are trying to get data. When the script loads, your callback function is executed and voila! - you have JSON data! This technique has 3 prerequisites.

  1. The service from which you are trying to request data returns JSON (either by default or on request using a parameter).
  2. The service supports JSONP by allowing you to specify a callback function in which to wrap the JSON data.
  3. You trust this external source enough to allow their code to execute on your site.
Jason Karns