(CORS) - Cross-Origin Resource Sharing connection issue - javascript

I am currently in the process of creating a browser extension for a university project. However as I was writing down the extension I hit a really weird problem. To understand fully my situation I will need to describe it in debt from where my issue comes.
The extension that I am currently working on has to have a feature that checks if the browser can connect to the internet or not. That is why I decided to create a very simple AJAX request function and depending on the result returned by this function to determine if the user has internet connection or not.
That is why I created this very simple AJAX function that you can see bellow this line.
$.ajax({
url: "https://enable-cors.org/index.html",
crossDomain: true,
}).done(function() {
console.log("The link is active");
}).fail(function() {
console.log("Please try again later.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So far, as long as I understand what it is doing, it is working fine. For example, if you run the function as it is, it will succsesfully connect to the url and process with the ".done(function..." if you change the url to "index273.index" a file which does not exist it will process with the ".fail(function...". I was happy with the result until I decided to test it further more and unpluged my cable out of my computer. Then when I launched the extension it returned the last result from when the browser had connection with the internet. My explanation why the function is doing this is because it is caching the url result and if it cannot connect it gives the last cached value. My next step to try and solve this was to add "cache: false" after the "crossDomain: true" property but after that when I launch the extension it gives the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://enable-cors.org/index?_=1538599523573. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
If someone can help me out sorting this problem I would be extremely grateful. I would want to apologise in advance for my English but this is not my native language.
PS: I am trying to implement this function in the popup menu, not into the "content_scripts" category. I am currently testing this under Firefox v62.0.3 (the latest available version when I write this post).
Best regards,
George

Maybe instead of calling the URL to check if the internet connection is available you could try using Navigator object: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection

unless the remote server allowed origin (allowed cors) then you can't access it because it's a security issue.
But there are other things you can do:
You can load image and fire event when an image is loaded
You can access remote JSON via JSONP response
but you can't access other pages because (unless that server allows it) it's a security issue.

Related

How to get the status code of the page before it is loaded

There is a javascript line (you can try it in the browser console)
window.location.href='http://example.com'
that will push you to http://example.com
In the Browser(Google Chrome)-> Developer Tools-> Network section you may see the Status is 200 for it.
The question is:
how to get the status code 200/404/302 right BEFORE executing
window.location.href='http://example.com'
Thank you.
P.S. jQuery is OK for using.
The only way to get the status code would be to make the request before you navigate there. That means make an Ajax call to the resource and check the status. Only downside to this is the Same Origin Policy so the sites need to be in the same domain or they have to have CORS enabled for your resource.
The HTTP status code are generated by the server, so some HTTP request against the server needs to be executed BEFORE you can get a status code -- so you would need to do an Ajax call on the url -- adapting the simple example in JQuery.get you will have something like;
$.get( "http://example.com", function( data ) {
// Yeahh the URL works, we can do the page switch
window.location.href='http://example.com';
});
There are other examples in JQuery.get which deals with error handling etc, but you can read those for yourself.
Of cause, you don't need the entire page to get just the status, you can execute just a HTTP-HEAD which you can see discussed here
With all of this you may run into cross-site scripting restrictions which you can go an research separately -- there are lot of stack-overflow questions on that already.

XMLHttpRequest cannot load - file footer.html, "Error: Failed to execute 'send' on 'XMLHttpRequest'

I have two of the same site. My 1st site is http://educationaboveall.org/ and the 2nd is http://www.savantgenius.com .
1st site is loading properly on every device without any error but the 2nd (www.savantgenius.com) site is not loading properly in mobile and table devices. It is only loading properly in desktop browser. I have also found 32 console error.
Are there any jQuery issues? And please tell me how to be able to fix it.
I'm getting the "XMLHttpRequest cannot load
file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html.
Cross origin requests are only supported for HTTP." and "Error: Failed
to execute 'send' on 'XMLHttpRequest': Failed to load
'file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html"
error, but I don't know what's causing it nor how to fix it.
Please see the screenshot - http://prntscr.com/4fm0d8
I Think that you should call it from a http webserver and not like simple file in browser. This mean request a file in a web server like http://localhost/XML/catalog.html not from file:///E:/Projects/XML/catalog.html.
It is as the message says:
cannot load file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html. .
You are referencing to a file on a Windows boxes filesystem and not in a webservers folder.
Second: you have a CORS-issue (which in this case is caused by the filesystem reference)
Cross origin requests are only supported for HTTP
See MDN for more infos.
To solve the issue, you have to configure your webserver to allow such requests. Check your webservers manual.
I had the same problem with my InfluxDB connection and it turns out I did not prepend the URL settings in the datasource with 'http://'. This could be nicer in Grafana, e.g. mentioning there is no protocol defined for accessing the source.
In your case it's clear that you somehow configured Grafana to look for D:\, which is not accessible for your browser. So check your data source URL.

Steam API Get SteamID using Javascript

Been running into what appears to be the Same Origin Policy which is causing quite some headache!
To cut to the chase, I am essentially trying to acquire a user's steam64id when only supplied their username.
For example, my username: "Emperor_Jordan" I would go to:
http://steamcommunity.com/id/emperor_jordan?xml=1
And the steamid I need is right at the top. So I figured I would use JQuery Ajax to acquire this and parse out the id I need for later usage (steamapi usage requires the steam64id) as follows. Here is a snippet of the code in question:
$.ajax({
url: "http://steamcommunity.com/id/emperor_jordan/?xml=1",
datatype: "xml",
complete: function()
{
alert(this.url)
},
success: parse
});
function parse(xml)
{
alert("parsing");
_steamID = $(xml).find("steamID64").text();
}
The problem here is while I do get the alert for the completion, I never see "parsing". Ever. It never gets that callback, which leads me to believe I am running into the SOP (same origin policy).
Am I approaching this the wrong way, is there a workaround?
Thanks!
Correct. You are running into the same-origin policy:
XMLHttpRequest cannot load http://steamcommunity.com/id/emperor_jordan/?xml=1. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
and it looks like Steam does not offer a cross-origin solution like JSONP. That means you're back to the old-but-reliable solution: fetch the data on your server, not in the browser.
Some relevant feedback on the Steam Web API: https://developer.valvesoftware.com/wiki/Steam_Web_API/Feedback#API_Considerations_for_Web_Developers
You need to create a proxy server in Heroku in order to get the data. Cors is restricting us to call the data directly to our browser not server to server interaction. So we need a proxy server to send the requests and receive the data on our behalf. It's working for me.
Thanks in advance.

Why does this jQuery.ajax not raise an error?

We had an interesting issue this morning - the details of the issue itself aren't relevant here, and I already fixed it, but I did run into something strange, to me, about jQuery.
The site I am building internally runs on https, only, so Apache is set to redirect any inbound http request to its https equivalent. This redirect is working fine. But, I had a bug in my software where I was trying to send the following ajax request:
jQuery.ajax({ type: "PUT",
url: "http://somewhere.com/cmdt/todo_lists/8457/toggle",
data: { deployment_id: 827},
dataType: "script"});
I understand that this would fail - I'm alright with jQuery not wanting to follow a redirect. But the actual behaviour is even weirder: I never see an xhr request go out at all! And there's no javascript error! It just fails, silently. If I change the url to https, or to a relative path, it works fine, no problem. My question is, why wasn't it TRYING to send out the request before? And why didn't it raise an error?
The reason you're not getting a failure is because it's a cross-site request, and so instead of using XMLHttpRequest, it's actually generating an HTML <script> tag and dropping it into the DOM, and using that mechanism to load the file.
This works reasonably well (considering it's a complete hack around wrong-headed browser "security" notions) but there's no way for jQuery to trap errors at that point, sadly. You will likely get a browser error if you have developer mode turned on, but that's it.
If you run that from an url that's https and try to open the equivalent http page you run into cross domain problems due to the different protocols they use. Have a look at same origin policy.

How to post a file and parse an xml reply in Internet Explorer 7

I have written a web application that posts a file via http to a restful web service. The web service can reply with a 400 or 403 response if the service finds any problems with the request. The response also contains xml describing the reason(s) for replying with a http error code.
My web application posts the file to a hidden iFrame and uses the iFrame's onload event handler to execute a function that parses the server response presented in the iFrame and let's the user know how the file upload went.
My solution works great with firefox and chrome but not in internet explorer 7.
My problem is that if the server responds with an error code e.g. 400 or 403 internet explorer 7 loads its own static error page. This means that my script can't parse the error message sent in the response since the static error page is not from the same domain as the script itself and violates the same origin policy (and since it's a static error page the web service's detailed error message won't be there anyway).
I see only two workarounds to this problem and I would prefer to avoid them both if possible:
A) Have the web service return 200, when the user-agent indicates internet explorer, even though an error has occured but include a xml response that indicates an error.
B) Have the web application post to an "intermediary" that forwards the request to the web service, reads the response and then translates it to a 200 or anything else that works (so it's basically option A but more flexible and at least this keeps the restful web service "clean").
Is there another way to solve my problem?
Assuming you have control of the server, you may find the best solution is to use the iframe only for sending the file (i.e. one way....client to server). Then use an ajax polling solution to determine whether or not the post was successful. It can be a bit messy, but should be much more reliable, and you can also get information back before the post is complete.
I managed to solve this since a colleague remembered that if the response body is not of a certain length when sending a 4xx response, Internet Explorer will load its static error page.
The workaround is to send back a longer response body with your 4xx response, e.g. a xml-comment containing white space.

Categories

Resources