contentScript having CORS issue with $.ajax() - javascript

I got this error expecting $.ajax() to work in my contentScript
XMLHttpRequest cannot load http://example.com/tab/index.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://gncbffieahbpgabchdjmhipkmahk****' is therefore not allowed access.
This is how the ajax look like in my contentscript.js
$.ajax({type: "GET",url: "http://example.com/tab/index.php", success: function(data){
alert(data);
}});
and in my http://example.com/tab/index.html I already declared
header('Access-Control-Allow-Origin: *');
Any idea why it still doesn't work?

This is most certainly not an issue on the extension side. It clearly says that the response does NOT contain the required header. You can confirm that in the Network tab of Dev Tools.
Look at your server-side code, but this question is unanswerable.
Unless, of course, you are willing to add your site to the permissions. Then CORS headers do not matter anymore.

It looks like the server doesn't allow Cross-Domain requests...
Just try JSONP (there's an example here)

Related

CORB from Vanilla JS getJSONP to Google Apps Script [duplicate]

I have called third party API using Jquery AJAX. I am getting following error in console:
Cross-Origin Read Blocking (CORB) blocked cross-origin response MY URL with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
I have used following code for Ajax call :
$.ajax({
type: 'GET',
url: My Url,
contentType: 'application/json',
dataType:'jsonp',
responseType:'application/json',
xhrFields: {
withCredentials: false
},
headers: {
'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'GET',
'Access-Control-Allow-Headers':'application/json',
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("FAIL....=================");
}
});
When I checked in Fiddler, I have got the data in response but not in Ajax success method.
Please help me out.
dataType:'jsonp',
You are making a JSONP request, but the server is responding with JSON.
The browser is refusing to try to treat the JSON as JSONP because it would be a security risk. (If the browser did try to treat the JSON as JSONP then it would, at best, fail).
See this question for more details on what JSONP is. Note that is a nasty hack to work around the Same Origin Policy that was used before CORS was available. CORS is a much cleaner, safer, and more powerful solution to the problem.
It looks like you are trying to make a cross-origin request and are throwing everything you can think of at it in one massive pile of conflicting instructions.
You need to understand how the Same Origin policy works.
See this question for an in-depth guide.
Now a few notes about your code:
contentType: 'application/json',
This is ignored when you use JSONP
You are making a GET request. There is no request body to describe the type of.
This will make a cross-origin request non-simple, meaning that as well as basic CORS permissions, you also need to deal with a pre-flight.
Remove that.
dataType:'jsonp',
The server is not responding with JSONP.
Remove this. (You could make the server respond with JSONP instead, but CORS is better).
responseType:'application/json',
This is not an option supported by jQuery.ajax. Remove this.
xhrFields: {
withCredentials: false },
This is the default. Unless you are setting it to true with ajaxSetup, remove this.
headers: {
'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'GET',
'Access-Control-Allow-Headers':'application/json',
},
These are response headers. They belong on the response, not the request.
This will make a cross-origin request non-simple, meaning that as well as basic CORS permissions, you also need to deal with a pre-flight.
In most cases, the blocked response should not affect the web page's behavior and the CORB error message can be safely ignored. For example, the warning may occur in cases when the body of the blocked response was empty already, or when the response was going to be delivered to a context that can't handle it (e.g., a HTML document such as a 404 error page being delivered to an tag).
https://www.chromium.org/Home/chromium-security/corb-for-developers
I had to clean my browser's cache, I was reading in this link, that, if the request get a empty response, we get this warning error. I was getting some CORS on my request, and so the response of this request got empty, All I had to do was clear the browser's cache, and the CORS got away. I was receiving CORS because the chrome had saved the PORT number on the cache, The server would just accept localhost:3010 and I was doing localhost:3002, because of the cache.
Return response with header 'Access-Control-Allow-Origin:*'
Check below code for the Php server response.
<?php header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode($phparray);
You have to add CORS on the server side:
If you are using nodeJS then:
First you need to install cors by using below command :
npm install cors --save
Now add the following code to your app starting file like ( app.js or server.js)
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
//enables cors
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
require('./router/index')(app);
It's not clear from the question, but assuming this is something happening on a development or test client, and given that you are already using Fiddler you can have Fiddler respond with an allow response:
Select the problem request in Fiddler
Open the AutoResponder tab
Click Add Rule and edit the rule to:
Method:OPTIONS server url here, e.g. Method:OPTIONS http://localhost
*CORSPreflightAllow
Check Unmatched requests passthrough
Check Enable Rules
A couple notes:
Obviously this is only a solution for development/testing where it isn't possible/practical to modify the API service
Check that any agreements you have with the third-party API provider allow you to do this
As others have noted, this is part of how CORS works, and eventually the header will need to be set on the API server. If you control that server, you can set the headers yourself. In this case since it is a third party service, I can only assume they have some mechanism via which you are able to provide them with the URL of the originating site and they will update their service accordingly to respond with the correct headers.
If you are working on localhost, try this, this one the only extension and method that worked for me (Angular, only javascript, no php)
https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc/related?hl=en
In a Chrome extension, you can use
chrome.webRequest.onHeadersReceived.addListener
to rewrite the server response headers. You can either replace an existing header or add an additional header. This is the header you want:
Access-Control-Allow-Origin: *
https://developers.chrome.com/extensions/webRequest#event-onHeadersReceived
I was stuck on CORB issues, and this fixed it for me.
have you tried changing the dataType in your ajax request from jsonp to json? that fixed it in my case.
There is an edge case worth mentioning in this context: Chrome (some versions, at least) checks CORS preflights using the algorithm set up for CORB. IMO, this is a bit silly because preflights don't seem to affect the CORB threat model, and CORB seems designed to be orthogonal to CORS. Also, the body of a CORS preflight is not accessible, so there is no negative consequence just an irritating warning.
Anyway, check that your CORS preflight responses (OPTIONS method responses) don't have a body (204). An empty 200 with content type application/octet-stream and length zero worked well here too.
You can confirm if this is the case you are hitting by counting CORB warnings vs. OPTIONS responses with a message body.
It seems that this warning occured when sending an empty response with a 200.
This configuration in my .htaccess display the warning on Chrome:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST,GET,HEAD,OPTIONS,PUT,DELETE"
Header always set Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]
But changing the last line to
RewriteRule .* / [R=204,L]
resolve the issue!
I have a similar problem. My case is because the contentType of server response is application/json, rather than text/javascript.
So, I solve it from my server (spring mvc):
// http://127.0.0.1:8080/jsonp/test?callback=json_123456
#GetMapping(value = "/test")
public void testJsonp(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
#RequestParam(value = "callback", required = false) String callback) throws IOException {
JSONObject json = new JSONObject();
json.put("a", 1);
json.put("b", "test");
String dataString = json.toJSONString();
if (StringUtils.isBlank(callback)) {
httpServletResponse.setContentType("application/json; charset=UTF-8");
httpServletResponse.getWriter().print(dataString);
} else {
// important: contentType must be text/javascript
httpServletResponse.setContentType("text/javascript; charset=UTF-8");
dataString = callback + "(" + dataString + ")";
httpServletResponse.getWriter().print(dataString);
}
}
Response headers are generally set on the server. Set 'Access-Control-Allow-Headers' to 'Content-Type' on server side
I had the same problem with my Chrome extension. When I tried to add to my manifest "content_scripts" option this part:
//{
// "matches": [ "<all_urls>" ],
// "css": [ "myStyles.css" ],
// "js": [ "test.js" ]
//}
And I remove the other part from my manifest "permissons":
"https://*/"
Only when I delete it CORB on one of my XHR reqest disappare.
Worst of all that there are few XHR reqest in my code and only one of them start to get CORB error (why CORB do not appare on other XHR I do not know; why manifest changes coused this error I do not know). That's why I inspected the entire code again and again by few hours and lost a lot of time.
I encountered this problem because the format of the jsonp response from the server is wrong. The incorrect response is as follows.
callback(["apple", "peach"])
The problem is, the object inside callback should be a correct json object, instead of a json array. So I modified some server code and changed its format:
callback({"fruit": ["apple", "peach"]})
The browser happily accepted the response after the modification.
Try to install "Moesif CORS" extension if you are facing issue in google chrome. As it is cross origin request, so chrome is not accepting a response even when the response status code is 200

Permanent Solution for "No 'Access-Control-Allow-Origin' header is present on the requested resource"

I have seen this problem quite a few times and it pops up time and again. This is a CORS(i.e. Cross origin request issue).The exact error I got this time is as follows:
XMLHttpRequest cannot load
https://myURL/myappdomain.subdomain.qual1/$count. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
Following are the possible solutions I have worked out in past. But they dont always work. They are URL specific solutions:
1) Having CORS plugin on chrome installed
2) Disabling web security from command line "--disable-web-security"
3) using 'jsonp' as format instead of 'json'
4) toggling cross-origin to "true" or "false".
Questions I need answer for
1) Why do we get this error? Is it something that the Server is imposing on the client pages?
2) What is the safest way to solve this? i.e. The method in which there is not security vulnerability and a reliable method.
3) Why cors is never an issue for API calls made from within nodeJS code?

Resolve "No 'Access-Control-Allow-Origin' header is present" issue with Chrome Extension

I am developing a Chrome Extension that pre-populates fields then submits the form on an external website when I visit it.
It works perfectly when the data is hard-coded into my script.js file.
However, I'd like to grab the username from an element in my Intranet home page & use this in the script instead of hard coding it.
I have made a simple script.js to test this works:
script.js:
$.get('https://intranet/index.php', function(data){
alert('test');
});
When I try to use this in my Extension and reload the page, I get the error:
XMLHttpRequest cannot load https://intranet/index.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://eecikfibchjhmochelhmhlimbcjglldf' is therefore not allowed access. The response had HTTP status code 401.
When this same code is run at https://intranet/test.html it works perfectly.
test.html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$.get('https://intranet/index.php', function(data){
$(document.body).load('https://intranet/ #username');
});
</script>
index.php:
<?php
header("Access-Control-Allow-Origin: *");
echo '<div id="username">username</div>';
?>
I have read that some use JSONP to resolve this issue. Does anyone have experience of this?
Can anyone provide help/advice on this issue?
Thank you for any guidance.
There seem to be two issues here at once.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Doesn't look like you thoroughly searched for solutions, since it's a common problem. Anyway, there are 2 ways to solve this:
On the extension side. If you have host permissions, you can do cross-origin requests regardless of CORS headers. (note: "When this same code is run at https://intranet/test.html it works perfectly" highlights that the issue is cross-origin but works on the same site).
There's a whole extension documentation article on this: Cross-Origin XMLHttpRequest, but an ultra-short version: you need to add permissions for the site in the manifest:
"permissions": [
"https://intranet/*"
],
On the server side, by adding a Access-Control-Allow-Origin: * header. Note that this solution opens a certain attack surface (not only your extension can do requests now), so approach 1 is preferable.
That said: you tried to implement approach 2, and it didn't work. Why? Because there is a second problem:
The response had HTTP status code 401
HTTP 401 is "Unauthorized". Your requests lack the authorization necessary - which you don't see when using the intranet site itself, since the browser already have those credentials cached.
But they won't be applied to cross-origin requests, so you get a 401 error page instead of the intended page - that doesn't contain your header.
You need to provide authorization along with the request. jQuery allows that:
$.get(
{
url: 'https://intranet/index.php',
username: '...',
password: '...'
}, function(data){
alert('test');
}
);
I think it should be obvious that this shouldn't be hardcoded in the extension.

No 'Access-control-allow-origin' header is present on the requested resource error with json and jquery

I use an API that is on a different server and i got an CORS error I think. The strange thing is that it first worked with no problem, then i got this error message
XMLHttpRequest cannot load http://www.thecocktaildb.com/api/json/v1/1/random.php? tagmode=any&type=POST&format=jsonp. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'myadress.com' is therefore not allowed acces
i added crossDomain: "true" and it worked for a day. Now it doesn't work again and i've searched and tried a lot of solutions i've found. But nothing works. What is the problem and how do i fix it? Tried jsonp instead of json with and without type:post and the &callback=? does nothing. I've even installed the CORS enable extension for chrome. But alwways the same error, I have no control over the API itself or the server hosting it. How can I fix this? Below is my code.
function random() {
$(document).ready(function () {
$.getJSON("http://www.thecocktaildb.com/api/json/v1/1/random.php", {
tagmode: "any",
type: "POST",
format: 'jsonp',
crossDomain: "true"
}, function (data) {
console.log(data);
var result = "";
$.each(data.drinks, function (index, value) {
result += "<p>" + value.idDrink + "<p>";
result += "<p>" + value.strDrink + "<p>";
});
$('#result').html(result);
console.log(result);
});
});
}
I think you can make some modification for bypass CORS error. but target environment can also block CORS request. When I used Paypal checkout, I encountered same problem. Paypal environment doesn't accept CORS request.
So that you can try to make this call over server side.
If I understood it right you are doing an AJAX call to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
Regular web pages can use the XMLHttpRequest object to send and
receive data from remote servers, but they're limited by the same
origin policy. Extensions aren't so limited. An extension can talk to
remote servers outside of its origin, as long as it first requests
cross-origin permissions.
Solution :
For allowing access to specific domain only:
response.addHeader("Access-Control-Allow-Origin", "http://www.thecocktaildb.com");
Check this blog post.

Why this won't fetch source code?

This code should fetch the HTML source of http://yahoo.com/(index.html), and show it in dialog.
$.ajax({ url: 'http://yahoo.com', success: function(data) {
alert(data);
}
});
However, it won't do anything...
What's wrong with my code?
By default, you're not allowed to make cross domain requests. This violate the Cross Origin policy.
To make it work the requested domain must emit headers that allow the requesting domain.
I've got a tutorial on how to set and use the CORS policy: http://fritsvancampen.wordpress.com/2013/02/03/cross-site-origin-requests-aka-cross-origin-resource-sharing/
but if you want to fetch data from Yahoo you need control over their domain .. and that's not gonna happen ;)
Ajax is not used for your purpose . you have to used like this
$content = file_get_contents('http://www.yahoo.com/');
print_r($content);
Or this could be helpful for you
http://toolspot.org/extract-website-data.php

Categories

Resources