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

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.

Related

REST API in Wordpress for affiliation system

I have a web page with links towards other web pages. Once an user clicks in one of those links, a cookie is created, so in case he makes a purchase in the web page, the info related to this link is sent to us through an "API call".
So far, the code I have used in the following:
var storeCookie = getCookie("COOKIE_NAME"); //gets the cookie if it was previously created
if(tiendaCookie!=""){
var request = new XMLHttpRequest();
var url="URL TO A .PHP FILE IN MY SERVER";
peticion.open("POST",url,true);
peticion.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
peticion.send("PARAMETERS OF THE CALL")
The web pages with links on our web page added this code to their web page so the affiliation system can work but we found that when that code is called, the following is returned:
Cross-Origin Read Blocking (CORB) blocked cross-origin response "URL TO A .PHP FILE IN MY SERVER" with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
I know this is not the right way to set up an API endpoint but I have no knowledge about how to proceed. I was going to try this plugin (https://wordpress.org/plugins/rest-api/) but it looks it is not supported in the latest versions of Wordpress.
What would be the right way to do what I am trying?
Thank you.
EDIT
I have done some more research and I have discovered that the problem might be in my .PHP file, because of:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
But I have this code on the .PHP file:
header("Access-Control-Allow-Origin: *");
What can I be missing?

AJAX result does not show up using HTTPS

My website is www.yourentacar.co.uk
when I navigate to the website using http 
http://www.yourentacar.co.uk 
write any letters in the search box 
AJAX returns results.
The problem occurs when I navigate to the website using https
https://www.yourentacar.co.uk
write any letters in the search box
the page is frozen and I do not get any result.
I have been trying to solve this problem for several days but I can't find a solution.
Such a problem is normally due to CORS issue, where a page on HTTP is not allowed to make a request to HTTPS unless allowed specifically via 'Access-Control-Allow-Origin' header.
If you open console, you might see an error like this
XMLHttpRequest cannot load [your api including protocol]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin [your domain including protocol] is therefore not allowed access.
You can fix this a few ways.
Make your site always run on https
Set Access-Control-Allow-Origin on your ajax call to allow non ssl domain to visit it, in your case.. something like header Access-Control-Allow-Origin: http://www.yourentacar.co.uk

contentScript having CORS issue with $.ajax()

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)

how Postman send requests? ajax, same origin policy

I have found this very useful Chrome extension called Postman. This is a very useful extension especially when you are into programming RESTful applications.
One thing I am confused on is that how this plugin/extension able to send POST request successfully on different domains?
I tried voting in a poll using Postman like this.
After submitting that, the vote was actually counted in, but when I tried doing that using AJAX and JavaScript, it fails, because of different origin policy of browsers.
How is that even possible?
Here is my code using jQuery. I used that in my computer though, localhost.
init: function() {
$.ajax({
url: 'http://example.com/vote.php',
type:'POST',
dataType: 'html',
data: {
id: '1'
},
success: function(data) {
if ( data == 'voted' ) {
$('.set-result').html( 'you already voted. try again after 24 hours' );
} else {
$('.set-result').html( 'successfully voted' );
}
}
});
},
Chrome packaged apps can have cross domain permissions. When you install Postman it promts you that this app will access any domain.
By placing */* in permissions section of your manifest file, you can do this.
Read more here:
https://developer.chrome.com/extensions/xhr.html
You can add the following header to sent Ajax request in postman.
Content-Type application/json
X-Requested-With XMLHttpRequest
Screenshot
Sounds like the site that hosts the poll (the "vote.php" script) needs to have an "Access-Control-Allow-Origin" header set to allow posting from a list of sites (or all sites).
A value of * for the header will allow posting from any website:
Access-Control-Allow-Origin: *
i.e. You could put the following at the top of vote.php
header('Access-Control-Allow-Origin: *');
Chrome extensions and apps are not subject to the same security limitations placed on normal webpages.
Additional debugging tips:
If you're trying to access remote services from web pages you have open on your local file system in your browser, you might find your browser applies different security rules to them than it does to files served from a web service.
e.g. If you open local files from a locational like C:\MyDocuments\weboot\index.htm (Windows) or \Users\joe\Sites\index.html (Mac) in your browser your AJAX request might not work, even with the header specified in most browsers.
Apple's Safari applies almost no cross domain restrictions to files opened locally but Firefox is much more strict about what it permits, with Chrome somewhere in the middle. Running a web server locally (e.g. on http://localhost/) is a good idea to avoid unexpected behaviour.
Additionally, other libraries that provide functions to handle Ajax requests (such as AngularJS) may require other headers to be set on the server by default. You can usually see the reason for failure in a browser debug console.
2021 Oct
In my investigation, I found out that you need an extra field in the header of your request. So simply add the following key-value into the header:
key: X-Requested-With | value: XMLHttpRequest

Chrome extension Cross Domain Request

I know that this has been talked about many times here, and I have read most of these threads but I can't seem to get my script working.
Problem is that I am trying to use bitly api to shorten urls in google chrome extension. I am saving users login and apiKey in localstorage and before I do so I validate them.
The code to do so is:
$.ajax({
url:"http://api.bit.ly/v3/validate",
dataType:'jsonp',
data:{
login: login,
apiKey: apiKey,
x_login :"test",
x_apiKey :"test"
},
success:function (jo, textStatus, jqXHR) {
if (jo.status_code == 200) {
setItem('dg_BitlyApiKey', apiKey);
setItem('dg_BitlyLogin', login);
alert('Saved');
} else {
alert('Incorrect login and/or apiKey!')
}
}
});
I do have my permissions set to "permissions": ["tabs", "notifications", "http://*/*", "https://*/*"] but I still keep getting:
Refused to load script from 'http://api.bit.ly/v3/validate?callback=jQuery17204477599645033479_1334062200771&login=&apiKey=&x_login=test&x_apiKey=test&_=1334062201506' because of Content-Security-Policy.
The script itself works outside the extension so I assume the problem isn't within the script but with the permissions.
What am I doing wrong here?
The problem is that you aren't really doing a XHR request, you're doing a JSONP request on an insecure HTTP resource. See the question How to load an external JavaScript inside an extension popup and the related Chromium bug report.
Yeah, we're no longer allowing insecure scripts in extensions. If you load a script over HTTP, an active network attacker can inject script into your extension, which is a security vulnerability.
JSONP operates by dynamically adding a new script tag into your page and then executing the contents. In your case, the script resource is fetched over HTTP (instead of HTTPS). If your extension uses version 2 of the extension manifest, its background pages cannot fetch non-HTTPS scripts.
Solution: If you use the Bitly API over HTTPS, I believe that will fix your issue. Send your Ajax call to https://api-ssl.bitly.com/v3/validate (instead of your current value of http://api.bit.ly/v3/validate)
You need to package your app/extension for cross domain requests to work. A hosted application will not be able to do cross domain requests. See:
Cross-Origin XMLHttpRequest in chrome extensions
To make Cross-Origin Requests in Chrome Extension you need to Avoid Cross-Origin Fetches in Content Scripts.
Full answer you can found in
https://stackoverflow.com/a/56929473/3680164
Or in the documentation
https://www.chromium.org/Home/chromium-security/extension-content-script-fetches

Categories

Resources