I have a local html file with an ajax function trying to pull a xml content from x.com. The file when run works only on IE and fails on firefox and safari browsers. Ofcourse this may be because of the Same origin policy. But,I have heard from someone that for scripts loaded using file:// protocol,this same origin policy will not apply. Is it true and if yes, what can be problem with my local html file?
You can allow Cross Domain Ajax calls to an application by just registering a new filter and then configure it to Allow-Origin : {your domain's} or you can use a wild card “*” to allow the calls from all domains.
CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.
Clicking the "Fetch HTML5 Rocks" button generates an Ajax call (via jQuery's $. ajax method) to http://www.html5rocks.com/en/tutorials/file/xhr2/. We set local JavaScript variable article to the contents of the first article found in the returned response and display the contents on our page.
Cross-origin resource sharing (or CORS) can be used to make AJAX requests to another domain. We'll look at how to set up CORS on the server in PHP, how to make the request in JavaScript and some considerations. CORS as a concept is broader than just AJAX requests but this is it's main use.
It is indeed applied to local files, treating them all as separate domains (this varies by browser, as you're seeing). For example in Chrome you can launch it with a command line to allow this:
chrome.exe --allow-file-access-from-files
In Mozilla file uri have even stricter same origin policy restrictions.. https://developer.mozilla.org/En/Same-origin_policy_for_file:_URIs However you can over-ride by asking for permission for global access using:
if (navigator.userAgent.indexOf("Firefox") != -1) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}
catch (e) {
alert("Permission UniversalBrowserRead denied -- not running Mozilla?");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With