How to perform cross domain requests locally in JavaScript/Chrome? - javascript

I am developing a test page, which will used only by myself and only with Google Chrome. Is there any way to perform cross domain requests to 3rd party server (which doesn't allow such requests) with such conditions? The requests could be GET or OPTIONS.
(I am aware about Chrome extensions like Advanced REST client, which could perform such requests, but it doesn't help me since complex calculations should be performed prior to request execution)

One option is to disable the same-origin policy entirely, as detailed in Disable same origin policy in Chrome. This will probably do the trick for you, but it's a bit inelegant, as it turns off the same-origin policy for the entire browser instance.
A second option is to create a small Chrome extension that holds all of the files that you need to load. It will make your files accessible via chrome-extension://... and only files within that extension will be immune from the same-origin policy.
Create a new folder, put your testing Web page in it, and create a manifest.json file in the same folder:
/testing_extension
test_page_immune_from_same_origin.html
script_used_by_test_page.js
styles_for_test_page.css
manifest.json
The contents of manifest.json should be
{
"name": "All-origin access extension",
"manifest_version": 2,
"version": "1.0",
"permissions": ["<all_urls>"]
}
Load the extension by going to chrome://extensions, enabling Developer Mode, and selecting the new folder with Load unpacked extension... option.
You can view your page as an extension resource chrome-extension://[app_id]/[file_name], where "app_id" is the hash listed for the extension on the chrome://extensions page. (It will be a long string of lowercase letters.) Now when the page performs cross-origin resources, it does so with the authority of a browser extension, unrestricted by the same-origin policy.
Note that you will need to move any inline scripts into separate files in order to comply with extension CSP requirements.

One way is to serve your files off a webserver rather than the local file system. Another way is to start Chrome with a flag:
chrome --disable-web-security
(From Cross-origin image load denied on a local image with THREE.js on Chrome)
A more extensive list of flags is here: http://peter.sh/experiments/chromium-command-line-switches/

I'm working on a project similar to this and I had to upload a simple html file to one of my prod servers for testing so I could test the cross domain functionality.
The html file pointed to localhost, so it would only work for me while in development.
The jquery code looked like this (just in case it helps):
$.ajax({
type: "POST",
dataType: "json",
cache: false,
url: url,
data: data,
crossDomain: true,
success: function (data) {
ATSJBAjax = null;
if (callback != null) callback(data);
}
});
Also I'm using c#/MVC, and I had to add an attribute to all controller methods that added "Access-Control-Allow-Origin" to the response header so Chrome would be OK with it. I called the attribute "AllowCrossDomainAccess", which ref'd the class below:
public class AllowCrossDomainAccessAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}

Related

Chrome Extension Not Sending Request [duplicate]

I've written a Chrome Extension for my library. It makes an AJAX call to api.library.edu (school's library).
My extension uses jQuery and my code looks like this:
$.get("http://api.library.edu/?period=1month", function (data) {
// process data
});
When I load my Extension, it makes the AJAX call and I get data back.
Right now I give absolutely no permissions to my extension (permissions is []).
Is my extension going to work when I publish it? Shouldn't it require special permissions to make AJAX calls with jQuery?
Thanks! I'm just making sure I wrote my extension correctly.
Your extension does not need any additional permissions to make AJAX calls from within the same origin. However, if api.library.edu does not set the proper CORS headers, you may need to request cross-origin permission for that domain:
{
"name": "My extension",
...
"permissions": [
"http://api.library.edu/"
],
...
}
From Google's Docs:
Each running extension exists within its own separate security origin. Without requesting additional privileges, the extension can use XMLHttpRequest to get resources within its installation.
...
By adding hosts or host match patterns (or both) to the permissions section of the manifest file, the extension can request access to remote servers outside of its origin.
If your extension is already working though, that would lead me to believe that the library API already has cross-domain headers set, and that you will not need any additional permissions.

Why can't load js file in my local apache2 server?

In my local domain's webpage , both
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
jq.src = http://127.0.0.1/js/jquery-3.3.1.min.js
can be loaded.
In the stackoverflow's webpage,right click to enter into chrome's inspect--console.
const jq = document.createElement('script');
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
document.head.appendChild(jq);
jq.addEventListener('load', () => {
console.log("hello world");
console.log($ === jQuery);
});
The remote jquery.js file can be loaded,now to replace it with local js file--http://127.0.0.1/js/jquery-3.3.1.min.js .
Why can't load the js file in my local apache2?
Sites you are visiting can apply security policy for javascript - which includes the debugger. I think what you are seeing is the application of the content security policy associated with the web page you are visiting.
You can see this in the page headers. In Chrome (as explained here), you can view the html headers sent with the page:
Open the developer panel, select the "network" tab, and reload the page.
For stackoverflow, look under the "name" column for "stackoverflow.com" - there may be two if you originally loaded it via http, so find the one which is https - probably the second one. Click that one, and select the "headers" tab on the right. You will see in amongst the response headers:
content-security-policy: upgrade-insecure-requests
This is explained here.
Basically, it tells the browser that all http requests should be "upgraded" to https. So when you try to access http://127.0.0.1/..., your browser upgrades the request to https://127.0.0.1/..., which your local server probably isn't set up to handle.
This is not limited to Chrome - all modern browsers should do this.
I browsed, for example, a few sites with Safari, and, in some cases, got an error message, such as on GitHub:
Refused to load https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js because
it does not appear in the script-src directive of the Content Security Policy.
That is another variety of content security policies you can read about here.
try
jq.setAttribute('src',"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js");
jq.setAttribute('crossOrigin',"Anonymos")
jq.onload=onFinish;

External file fail to load on 'load' function

I want to load content of external text file (demo.txt) in my div on button click.
Text file containes text 'Demo text.'
But it shows error
XMLHttpRequest cannot load file:///C:/Users/Tom/Desktop/jQuery%20thenewboston/76.)%20Load%20function/demo.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
on my browser console.
$(document).ready(function(){
$('#button_file').on('click',function(){
$('#load_html').load('demo.txt');
});
});
<button type="button" id="button_file">Load file</button>
<br />
<div id="load_html" >
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am a beginner in jquery , please comment below for any query.
You cannot get the result because the remote site doesn't have CORS enabled: If you look at the console, you'll see:
(Reason: CORS header 'Access-Control-Allow-Origin' missing).
You can bypass CORS by using something like anyorigin.com, i.e.:
$.getJSON('http://anyorigin.com/get/?url=http%3A//thenewboston....&callback=?', function(data){
$('#div-data').html(data.contents);
});
PS: If it's a local file, make sure you load it on the same address as the script, (localhost, 127.0.0.1, 192.168.1.1, etc...)
You are being restricted by HTTP access control (CORS). The file you are requesting asynchronously needs to be from the same domain or the domain you are accessing it from needs to allow your domain to access it. As you are using the file:/// protocol you need to allow it, so check out this if that's the way you wish to go.
Alternatively you can create a local web server to host your site an allow access to the file on the same domain.
In order to make this work you need to use a web server instead of using just clicking on the html file.
Check XAMPP
Unfortunately, Google Chrome doesn't allow cross-origin request although Firefox does.
Alternatively, if the text file is short you can store it in an object and place it wherever you like.
text_file = {
contents = 'content';
}
$('.button_class').on('click',function(){
$('.div').html(text_file.contents);
});
I would never suggest you use this but if it's a small project, a one page application that nobody will see the code to - desperate times call for desperate measures.
The best thing to do is to use XAMPP and PHP.
Load in from your database the content you would like to show.
You can read the PHP documentation or watch online tutorials , I personally suggest TheNewBoston PHP Tutorials with Alex Garrett

How To Reach Local Insecure (HTTP) Server From A Secure (HTTPS) Page

I have a site running on https, which is trying to reach a windows service that is running as an http server, using an http localhost address, via AJAX. However, this is returning an "Access is denied" error. It works fine when calling from http, but that is not an option beyond testing. We are also limited to using Internet Explorer (9+) only.
I have set the "Allow mixed content" security setting to "Enable" for the respective zone, but it is still getting blocked.
The AJAX call looks like this:
$.ajax({
url: 'http://localhost:5923/somefunction',
data: {
sid: sid,
aid: aid
},
success: function (ret) {
//...
},
error: function (error, status, errThrown) {
alert(errThrown);
}
});
I know modifying the windows service to function over https is the best solution long term, but does anyone have any suggestions for IE settings that would allow mixed active content, or any other interim fixes?
Thanks in advance.
You need to enable cross-origin access so go to Tools->Internet Options->Security tab, click on “Custom Level” button for the zone of your choice. Go to Miscellaneous -> Access data sources across domains setting and select “Enable” option.
Is this code blocked by SOP (Same Origin Policy)?
If so, set "crossDomain" setting to "true".
http://api.jquery.com/jquery.ajax/

What permissions (if any) I need to give my Chrome Extension to let it make remote AJAX calls?

I've written a Chrome Extension for my library. It makes an AJAX call to api.library.edu (school's library).
My extension uses jQuery and my code looks like this:
$.get("http://api.library.edu/?period=1month", function (data) {
// process data
});
When I load my Extension, it makes the AJAX call and I get data back.
Right now I give absolutely no permissions to my extension (permissions is []).
Is my extension going to work when I publish it? Shouldn't it require special permissions to make AJAX calls with jQuery?
Thanks! I'm just making sure I wrote my extension correctly.
Your extension does not need any additional permissions to make AJAX calls from within the same origin. However, if api.library.edu does not set the proper CORS headers, you may need to request cross-origin permission for that domain:
{
"name": "My extension",
...
"permissions": [
"http://api.library.edu/"
],
...
}
From Google's Docs:
Each running extension exists within its own separate security origin. Without requesting additional privileges, the extension can use XMLHttpRequest to get resources within its installation.
...
By adding hosts or host match patterns (or both) to the permissions section of the manifest file, the extension can request access to remote servers outside of its origin.
If your extension is already working though, that would lead me to believe that the library API already has cross-domain headers set, and that you will not need any additional permissions.

Categories