Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to bypass Javascript / jQuery's same origin policy for local access?

Trying to use ajax, getJSON, and functions like that to fetch an external URL from a local (non-server) development computer. Is there a way to bypass the same origin policy, so that I can test locally, instead of having to upload to a server?

like image 298
ina Avatar asked Aug 14 '10 04:08

ina


3 Answers

Here's the simple answer: chrome --disable-web-security

From the source code (chrome_switches.h):

// Don't enforce the same-origin policy.  (Used by people testing their sites.)
const char kDisableWebSecurity[]            = "disable-web-security";

I wanted to use jquery.js to send AJAX calls to a Google Apps python server running on port 8080. Just for testing, I wanted to run the browser and the server on the same machine.

I don't understand all the security nuances, but for temporary development it seems like a reasonable workaround. So long as I only use chrome for testing with this flag, it shouldn't be a problem.

Here's the whole command for Mac OS X:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security

like image 189
Vagrant Avatar answered Oct 20 '22 00:10

Vagrant


We had the same need when developing our web app. Here's how we did it:

The browser and the server communicate only through JSON.
All the HTML is rendered in the browser using PURE (our JS template engine).
The browser code is developed locally like this:

We add a host parameter in the url of the app:

http://localhost/app.html?host=test.beebole-apps.com

In production, the JSON are sent to the server with a POST.
But here the function in charge of the ajax call will react to the host parameter and make a JSONP injection(GET) instead.

<script src="http://test.beebole-apps.com/?callback=f2309892&json={...}" />
  • f2309892 is a temporary function, with a random name, that points to the method that will handle the response
  • json is the JSON we send to the server

It means you will need some cooperation from the backend to serve you the json wrapped in a callback function like:

f2309892( /*the json here*/ );

Except a size limitation(you can't send a big JSON to the server with a GET) it works like a breeze.
An other advantage is you can call all the different systems(development and test) from the same localhost.

like image 35
Mic Avatar answered Oct 19 '22 23:10

Mic


There are different ways to get around this, depending on which browser you're using for development. For example:

  • In Firefox (Gecko), set security.fileuri.strict_origin_policy to false
  • In Chrome, start the browser with the option --allow-file-access-from-files

References: Firefox, Chrome

like image 35
Ken Redler Avatar answered Oct 19 '22 23:10

Ken Redler