What is the clarification regarding accessing JSON from various domains?

(I am aware of the fact that ajax calls must originate from the same domain, and have already gone through relevant responses)

However, I am having trouble grasping something:

We often see platforms like Facebook use the for(;;) || while(1) pattern in their json responses:

And naturally, in order to extract and utilize the data, one must remove the for(;;) portion and then parse it accordingly.

I've been advised (by @esailija) that:

You can't strip away the for loop unless the request originates from the same domain, that's the crux of it

Alright, this is all due to the same origin policy.

But I have a question:

Consider John incorporating this on his website (john.com):

 some content...
   <script src="facebook.com/ajax/recent" type="text/javascript"></script>
 some content...

Notice how it's the same URL as Facebook's (indicated by my leftmost red arrow) -

Assumption

  • If he fetches the response using <scrip>...</script> and the result comes without for(;;), - he'll still be unable to do anything with {"__ar:1,....}! It would need to be padded (like jsonp) with myCallBack({"__ar:1,....});

What I mean is:

var a=1;

{"__ar:1,....}  <--- john won't be able to work with this.

var b=1;

Question :

What am I overlooking and are my assumptions accurate?

Answer №1

Back in the day, there was an issue with using a seemingly innocent array literal - it was not safe. For example, running code like this:

[1,2,3]

Would actually trigger the array constructor with those values, leading to potential harm as demonstrated below:

<script>
Array = function() {
     //Steal the values etc
};
</script>
<script src="facebook.com/yourtimeline.json"></script>
//the above code contains data structures that call the array constructor
//and I can access them.

In the past, if you visited my website on an older browser (think Firefox 2) while logged into Facebook, I could silently retrieve your data in the array constructor if there wasn't a for(;;). However, because it exists, my site will just keep looping endlessly.

Answer №2

Upon receiving the feedback and (like you mentioned) if it did not contain for(;;); at the start, then it would qualify as a valid segment of JavaScript code (an object initializer) with no assigned result. In such cases, it would execute without causing any harm. However, those safeguarding their JSON feeds do not want them to be innocuously executed when exploited inappropriately, hence they introduce this deliberate pollution at the beginning to make the misuse painful by triggering an endless loop.

The common procedure for accessing a feed contaminated with intentional pollution at the commencement involves ensuring that it originates from the same source (or at least one permitted by their CORS policy): You fetch the feed via ajax as plain text, remove the initial for(;;);, and proceed to interpret the remaining content as JSON data.

Answer №3

Your initial assumption may have been incorrect, however the second was spot on.

While it's true that you can't make an AJAX request to a different origin, you are able to load a script from a different origin. This is precisely how JSONP handles requests to different origins.

The JSONP format sets itself apart from regular JSON due to this very reason. It involves wrapping JSON data in a function call, allowing the response to be useful. As you guessed correctly, a plain JSON response would not serve any purpose when loaded as a script; it would just undergo evaluation and then be discarded.

Edit

In light of recent edits, the original assumption that the request wouldn't work at all has been omitted from the discussion.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP and MySQL to interact with Ajax for posting data

Having some trouble posting data to MySQL using PHP and Ajax. The issue seems to be with the javascript, specifically in the Ajax part. Can anyone help me fix it? If there are any errors in the code below, please point them out: FORM: <form id="conta ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

Regular expression for eliminating the local path from a website address

I am facing a scenario where different formats of relative paths can occur, such as: const URL1 = "./hello-world" const URL2 = "../hello-world" const URL3 = "../../hello-world" const URL4 = "../../../hello-world" con ...

Is it possible to find a more efficient approach than calling setState just once within useEffect?

In my react application, I find myself using this particular pattern frequently: export default function Profile() { const [username, setUsername] = React.useState<string | null>(null); React.useEffect(()=>{ fetch(`/api/userprofil ...

Preventing ReactJS tooltips from exceeding the boundaries of the screen

Here is a simple demo showcasing blocks with tooltips that appear when hovered over. However, there seems to be an issue with the functionality. The tooltip should ideally be displayed either from the left or right side of the block. To determine the size ...

Stop Cross-Site Scripting attacks in ajax by filtering the rsargs[]

While working on my php ajax site, I discovered a potential XSS vulnerability in the ajax library. The rsargs[] parameter is susceptible to attacks as it can accept any script or value. My attempts to mitigate this issue by using html encoding have been u ...

The list of data in the Jquery/Ajax success response is showing as "undefined."

I am facing an issue with my AJAX code. It retrieves a list from the controller, but when I display it, I receive an "undefined" message. AJAX $.ajax( { url: "/Panel/OpenOrderDetail1", type: 'GET&a ...

How can the ordering of dynamically generated components be synchronized with the order of other components?

Currently, I'm delving into Vue 3 and encountering a specific issue. The tabs library I'm using only provides tab headers without content panels. To work around this limitation, I've come up with the following solution: <myTabs/><!- ...

Encountering a 401 error while attempting to exchange Faceit OAuth authorization code for access token

I am having issues with exchanging a code for a token on the Faceit OAuth. The documentation states the following: Exchanging the Authorization Code for an Access Token The third-party app needs to make a server-to-server call, providing the Authorization ...

Exploring the magic of Asp.net Core 2.0 Razor Pages with Ajax Postions

I've been attempting to use a jQuery ajax call to fetch a list of users from a Razor page. Users.cshtml.cs page: public ActionResult OnPostList(string FirstName, string LastName,string IsActive) { var data = (from s in _db.SecurityUser ...

Javascript chart

Hello everyone, I am diving into the world of fetch API. Currently, I am faced with a challenge where I need to generate the following list items: <li>Zimmerman, Paul</li> <li>Yimmerman, Raul</li> <li>Limmerman, Caul</li> ...

Guide to updating the content div on a webpage without refreshing using Google App Engine

Currently, I am in the process of developing an application using GAE with Python and my main requirement is to create a chat system where multiple users can send messages to a single recipient. I initially explored using sockets but encountered issues wh ...

What is the best way to vertically align an InputLabel within a MUI Grid item?

I'm trying to vertically center the InputLabel inside a MUI Grid item. Here's what I've attempted: import { FormControl, Grid, Input, InputLabel, TextField } from "@mui/material"; export default function App() ...

What is the best method for developing a draggable element that remains stable?

I have developed a simple script for draggable elements, however, I am facing an issue. Whenever I move the mouse quickly, the element loses focus. Is there a way to improve the stability of the dragging functionality regardless of how fast I move the mou ...

Having trouble passing parameters to Next JS when using the Courtain.js library

Greetings everyone, I am in the process of developing a website and I have encountered an issue with inserting a distorted image with animation on the homepage. After using a library called Courtain.js, a developer managed to make it work and provided me ...

Modifying the Ext.js TreePanel checkbox component

I've implemented a basic tree panel checkbox example using Ext.js as shown below: Ext.onReady(function(){ var tree = new Ext.tree.TreePanel({ renderTo:'tree-div', title: 'My Task List', height: 300, ...

How to avoid property sharing in Angular recursive components

I am currently working on a recursive component that generates a tree structure with collapsible functionality. However, I am facing an issue where the state variable active is being shared among child components. Is there a way to prevent this from happen ...

Guide to transforming a JSON file value into a JavaScript list

I need assistance with converting a string of comma-separated values in a JSON file into a list. The goal is to iterate through the list in a for loop and click on each element. Can you help me with this task? testdata.json : {"optionsList":&quo ...

incorporating numerous interconnected javascript files within a single html document

I have a pair of JavaScript files (file1, file2). File1 utilizes a class that is defined in file2. Can I include these files in an HTML document like this: <script type="text/javascript" src="file1.js"></script> <script type="text/javascrip ...

Is it possible to retrieve all data from the Google translation API?

In my React app, the main component contains this function: componentDidMount(){ const land = ["Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Assamese", "Aymara", &qu ...