Getting Around Same-Origin Policy in Web Browsers
Web browsers enforce a security policy called “Same Origin Policy” in order to protect their users from attacks by malicious web sites. The “Same Origin” policy requires that any attempt by Javascript on a web page to access a web site must go to the same web site that the web page came from.
This protects the user from attacks where a page contains malicious code that would attempt to access another site that the user is currently logged in to and do things as that user that the user most likely wouldn’t want to do, for instance, use Facebook or Gmail to spam other users.
This is a good thing, but occasionally it gets in the way of developers who are trying to do something useful and not malicious. In my case, I’m writing a small Javascript-based app to run in a browser. The app needs to make asynchronous page fetches from web servers running on devices in my house in order to control them. The app utilizes Phonegap to allow it to run as a native iOS app, albeit browser-based. Phonegap disables Same Origin Policy in Mobile Safari (only for Phonegap apps), but I want to write it and debug it on a browser under MacOS X, which is a much more convenient environment to work in.
Thankfully, browsers often provide a way to allow developers to turn off Same Origin Policy temporarily. Unfortunately, different browsers do it different ways.
Google Chrome can be started with an option to turn off the Same Origin Policy. Unfortunately this disables it for the entire browser, until you restart it. I wish there were a way to do this for just one web page or tab.
open -a '/Applications/Chrome.app' --args --disable-web-security
C:\Program Files\Chrome\Chrome.exe --disable-web-security
(or wherever Chrome is stored on your computer)
Apple’s Safari offers a similar mechanism:
open -a '/Applications/Safari.app' --args --disable-web-security
C:\Program Files\Safari\Safari.exe --disable-web-security
Firefox has a nicer solution. Any Javascript application can request that Same Origin Policy be relaxed for it. The browser will confirm with the user.
try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } catch (e) { alert("UniversalBrowserRead failed"); }
These days I do most of my web development using Google’s Chrome, but Firefox’s solution to my problem will bring me back to it, at least for this project.
I’m developing under MacOS X so whatever difficulty there may be disabling Same Origin Policy in Internet Explorer doesn’t matter to me. I also don’t have any information on disabling it in Opera.