Intermittent jQuery failure in Chrome extension - javascript

I'm seeing a strange issue (only in production of course) where some $.post requests are failing intermittently with the error:
{"readyState":0,"status":0,"statusText":"error"}
I've looked into this and in most cases there seem to be two possible issues:
1) Cross domain errors. This shouldn't be an issue since the chrome extension is set up to be able to access the domain, additionally since it only fails sometimes this seems like it shouldn't be the issue
2) not calling e.preventDefault(). The request is being made from the background process so i don't think this is the issue. Again the fact that it is intermittent makes this unlikely.
Additionally it seems UNLIKELY that its purely network related since the only way we know about these issues are posting to an endpoint on our server to retrieve the errors...i.e. if the computer was offline, the request sent in the failblock should fail as well.
Are there any other known issues that could cause the query to fail with that error?
UPDATE
Here's some pseudo code for the way the request is made:
$.post(this._baseUrl + "/my_endpoint", JSON.stringify(data))
.done(function(res){
//SUCCESS!
})
.fail(function(error, textStatus, errorThrown) {
//{"readyState":0,"status":0,"statusText":"error"}
}.bind(this));

Related

How to detect if HTTP requests are blocked by a browser extension?

I am trying to detect if a user is using some kind of extension in his browser that could prevent my site from working properly and if so, display a message for the user.
I am testing with an extension called uMatrix, but there are others with a similar approach.
My problem is, that kind of extension will block my HTTP request, but that doesn't return a proper status code (like 403, 404, 500, etc). Instead, when I catch my request, I just get a
Error: Network Error
at [my file name and line number here]
at XMLHttpRequest.handleError (xhr.js:83)
I believe this same error would be thrown in other circumstances, like lack of internet connection, so I can't assume this Network Error means that the user has a "HTTP request blocker".
I was reading a lot about identifying AdsBlocker on this thread and other places, but I don't think it applies to my issue.
Any ideas on how to identify that a user is blocking my HTTP Requests? (Either on purpose or through a browser extension)
I thought I would share here the solution I found, even though I don't think that's the best answer yet.
I am using Axios for my API requests and I found this thread here:
https://github.com/axios/axios/issues/383#issuecomment-234079506
What they suggest it's to check if the response has a status (but in latest Axios, they don't even return a response). If not, it means the server was never reached. That could still mean that there is no internet connection, not necessarily an extension blocked the request. So I adjusted my message to cover both scenarios.
My final code was something like this:
// Note the use of "HEAD", since that will be faster than a "GET"
axios.head(server_url_for_testing).catch(function(error) {
if (!error.response) {
// Display my warning message
}
})

Problem with $.json return status 0 in Cordova when run from browser [duplicate]

For some reason, while using AJAX (with my dashcode developed application) the browser just stops uploading and returns status codes of 0. Why does this happen?
Another case:
It could be possible to get a status code of 0 if you have sent an AJAX call and a refresh of the browser was triggered before getting the AJAX response. The AJAX call will be cancelled and you will get this status.
In my experience, you'll see a status of 0 when:
doing cross-site scripting (where access is denied)
requesting a URL that is unreachable (typo, DNS issues, etc)
the request is otherwise intercepted (check your ad blocker)
as above, if the request is interrupted (browser navigates away from the page)
Same problem here when using <button onclick="">submit</button>. Then solved by using <input type="button" onclick="">
Status code 0 means the requested url is not reachable. By changing http://something/something to https://something/something worked for me. IE throwns an error saying "permission denied" when the status code is 0, other browsers dont.
It is important to note, that ajax calls can fail even within a session which is defined by a cookie with a certain domain prefixed with www. When you then call your php script e.g. without the www. prefix in the url, the call will fail and viceversa, too.
Because this shows up when you google ajax status 0 I wanted to leave some tip that just took me hours of wasted time... I was using ajax to call a PHP service which happened to be Phil's REST_Controller for Codeigniter (not sure if this has anything to do with it or not) and kept getting status 0, readystate 0 and it was driving me nuts. I was debugging it and noticed when I would echo and return instead of exit the message I'd get a success. Finally I turned debugging off and tried and it worked. Seems the xDebug debugger with PHP was somehow modifying the response. If your using a PHP debugger try turning it off to see if that helps.
I found another case where jquery gives you status code 0 -- if for some reason XMLHttpRequest is not defined, you'll get this error.
Obviously this won't normally happen on the web, but a bug in a nightly firefox build caused this to crop up in an add-on I was writing. :)
This article helped me. I was submitting form via AJAX and forgotten to use return false (after my ajax request) which led to classic form submission but strangely it was not completed.
"Accidental" form submission was exactly the problem I was having. I just removed the FORM tags altogether and that seems to fix the problem. Thank you, everybody!
I had the same problem, and it was related to XSS (cross site scripting) block by the browser. I managed to make it work using a server.
Take a look at: http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/282972/why-am-i-getting-xmlhttprequest.status0
We had similar problem - status code 0 on jquery ajax call - and it took us whole day to diagnose it. Since no one had mentioned this reason yet, I thought I'll share.
In our case the problem was HTTP server crash. Some bug in PHP was blowing Apache, so on client end it looked like this:
mirek#toccata:~$ telnet our.server.com 80
Trying 180.153.xxx.xxx...
Connected to our.server.com.
Escape character is '^]'.
GET /test.php HTTP/1.0
Host: our.server.com
Connection closed by foreign host.
mirek#toccata:~$
where test.php contained the crashing code.
No data returned from the server (not even headers) => ajax call was aborted with status 0.
In my case, it was caused by running my django server under http://127.0.0.1:8000/ but sending the ajax call to http://localhost:8000/. Even though you would expect them to map to the same address, they don't so make sure you're not sending your requests to localhost.
In our case, the page link was changed from https to http. Even though the users were logged in, they were prevented from loading with AJAX.
In my case, setting url: '' in ajax settings would result in a status code 0 in ie8.. It seems ie just doesn't tolerate such a setting.
For me, the problem was caused by the hosting company (Godaddy) treating POST operations which had substantial response data (anything more than tens of kilobytes) as some sort of security threat. If more than 6 of these occurred in one minute, the host refused to execute the PHP code that responded to the POST request during the next minute. I'm not entirely sure what the host did instead, but I did see, with tcpdump, a TCP reset packet coming as the response to a POST request from the browser. This caused the http status code returned in a jqXHR object to be 0.
Changing the operations from POST to GET fixed the problem. It's not clear why Godaddy impose this limit, but changing the code was easier than changing the host.
I think I know what may cause this error.
In google chrome there is an in-built feature to prevent ddos attacks for google chrome extensions.
When ajax requests continuously return 500+ status errors, it starts to throttle the requests.
Hence it is possible to receive status 0 on following requests.
In an attempt to win the prize for most dumbest reason for the problem described.
Forgetting to call
xmlhttp.send(); //yes, you need this pivotal line!
Yes, I was still getting status returns of zero from the 'open' call.
In my case, I was getting this but only on Safari Mobile. The problem is that I was using the full URL (http://example.com/whatever.php) instead of the relative one (whatever.php). This doesn't make any sense though, it can't be a XSS issue because my site is hosted at http://example.com. I guess Safari looks at the http part and automatically flags it as an insecure request without inspecting the rest of the URL.
In my troubleshooting, I found this AJAX xmlhttpRequest.status == 0 could mean the client call had NOT reached the server yet, but failed due to issue on the client side. If the response was from server, then the status must be either those 1xx/2xx/3xx/4xx/5xx HTTP Response code. Henceforth, the troubleshooting shall focus on the CLIENT issue, and could be internet network connection down or one of those described by #Langdon above.
In my case, I was making a Firefox Add-on and forgot to add the permission for the url/domain I was trying to ajax, hope this saves someone a lot of time.
Observe the browser Console while making the request, if you are seeing "The Same Origin Policy disallows reading the remote resource at http ajax..... reason: cors header ‘access-control-allow-origin’ missing" then you need to add "Access-Control-Allow-Origin" in response header. exa: in java you can set this like response.setHeader("Access-Control-Allow-Origin", "*") where response is HttpServletResponse.

Ajax chat program errors when retrieving messages [duplicate]

I keep receiving this error when I do some Ajax calls...
It may even be something to do with Geocoding but I really have no idea how to capture the error to display something useful to users... or even how to solve the problem as it seems to just be referencing some kind of pointer or something :S 0x2ef3
SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3.
An image might be more helpful than the error message:
Any ideas at all?
My code fires off 10 ajax calls in 1 second to be processed by geocoding server side.
The error comes up intermittently. Sometimes I get geocoded results and sometimes I get that error. I would say I get it 10% of the time. It completely stops the ajax call from firing my error handler in jQuery.
This is the fix that worked for me. There is invalid mime or bad characterset being sent with your json data causing that errror. Add the charset like this to help it from getting confused:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
});
Reference:
Jquery - How to make $.post() use contentType=application/json?
Could not complete the operation due to error c00ce56e
We also encountered similar problems. However, setting the charset as noted in the previous comment did not help. Our application was making an AJAX request every 60 seconds and our webserver, nginx, was sending Keep-Alive timeout at 60 seconds.
We fixed the problem by setting the keep-alive timeout value to 75 seconds.
This is what we believe was happening:
IE makes an AJAX request every 60 seconds, setting Keep-Alive in the request.
At the same time, nginx knows that the Keep-Alive timeout value is ignored by IE, so it starts the TCP connection close process (in the case of FF/Chrome this is started by the client)
IE receives the close connection request for the previously sent request. Since this is not expected by IE, it throws an error and aborts.
nginx still seems to be responding to the request even though the connection is closed.
A Wireshark TCP dump would provide more clarity, our problem is fixed and we do not wish to spend more time on it.
I received the same error (SCRIPT7002: XMLHttpRequest: Network Error 0x80004004, Operation aborted), in our case it was because of JavaScript's same origin policy.
Our web app was making a JQuery AJAX call to our server on Port 8080. The call was getting intercepted and re-routed over SSL (due to server rules mandating that incoming traffic use SSL).
Once we made our web app load through the SSL port the issue was fixed.
I had this problem, a an AJAX Post request that returned some JSON would fail, eventually returning abort, with the:
SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3
error in the console. On other browsers (Chrome, Firefox, Safari) the exact same AJAX request was fine.
Tracked my issue down - investigation revealed that the response was missing the status code. In this case it should have been 500 internal error. This was being generated as part of a C# web application using service stack that requires an error code to be explicitly set.
IE seemed to leave the connection open to the server, eventually it timed out and it 'aborted' the request; despite receiving the content and other headers.
Perhaps there is an issue with how IE is handling the headers in posts.
Updating the web application to correctly return the status code fixed the issue.
Hope this helps someone!
This issue happened in my project because of an ajax GET call with a long xml string as a parameter value. Solved by the following approach:
Making it as ajax post call to Java Spring MVC controller class method like this.
$.ajax({
url: "controller_Method_Name.html?variable_name="+variable_value,
type: "POST",
data:{
"xmlMetaData": xmlMetaData // This variable contains a long xml string
},
success: function(response)
{
console.log(response);
}
});
Inside Spring MVC Controller class method:
#RequestMapping(value="/controller_Method_Name")
public void controller_Method_Name(#RequestParam("xmlMetaData") String metaDataXML, HttpServletRequest request)
{
System.out.println(metaDataXML);
}
I had this error for some time and found a fix. This fix is for Asp.net application, Strange it failed only in IE non compatibility mode, but works in Firefox and Crome. Giving access to the webservice service folder for all/specific users solved the issue.
Add the following code in web.config file:
<location path="YourWebserviceFolder">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
I have stumbled across this questions and answers after receiving the aforementioned error in IE11 when trying to upload files using XMLHttpRequest:
var reqObj = new XMLHttpRequest();
//event Handler
reqObj.upload.addEventListener("progress", uploadProgress, false);
reqObj.addEventListener("load", uploadComplete, false);
reqObj.addEventListener("error", uploadFailed, false);
reqObj.addEventListener("abort", uploadCanceled, false);
//open the object and set method of call (post), url to call, isAsynchronous(true)
reqObj.open("POST", $rootUrlService.rootUrl + "Controller/UploadFiles", true);
//set Content-Type at request header.for file upload it's value must be multipart/form-data
reqObj.setRequestHeader("Content-Type", "multipart/form-data");
//Set header properties : file name and project milestone id
reqObj.setRequestHeader('X-File-Name', name);
// send the file
// this is the line where the error occurs
reqObj.send(fileToUpload);
Removing the line reqObj.setRequestHeader("Content-Type", "multipart/form-data"); fixed the problem.
Note: this error is shown very differently in other browsers. I.e. Chrome shows something similar to a connection reset which is similar to what Fiddler reports (an empty response due to sudden connection close).
Also, this error appeared only when upload was done from a machine different from WebServer (no problems on localhost).
I just want to add what solved this problem for me, as it is different to all of the above answers.
The ajax calls that were causing the problem were trying to pass an empty data object. It seems IE does not like this, but other browsers don't mind.
To fix it I simply removed data: {}, from the ajax call.
With the Apache 2 change KeepAliveTimeout set it to 60 or above
Upping the directive in the virtualhost for KeepAliveTimeout to 60 solved this for me.
Have encountered the same issue in my asp.net project, in the end i found the issue is with the target function not static, the issue fixed after I put the keyword static.
[WebMethod]
public static List<string> getRawData()
Incase none of these solutions were "clear" enough, essentially IE/Edge is failing to parse your "data" field of your AJAX call properly. More than likely you're sending an "encoded" JSON object.
What Failed:
"data": "{\"Key\":\"Value\"}",
What Works:
"data":'{"Key":"Value"}'
[SOLVED]
I only observed this error today, for me the Error code was different though.
SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete
the operation due to error 00002efd.
It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.

On Firefox, CORS request gives error ":" (colon)

On Chrome, I'm having no troubles making a cross domain request, however on Firefox (Ubuntu 14.04), I get an error that consists only of a colon on the line that calls for the xmlhttprequest.
xmlhttp.open("GET", "http://x.x.x.x:xxxx/folder/file.xml", false);
The error message is just ":".
Try Disabling AdBlock
I was having a similar issue where all of my XMLHttpRequests were going through except for a few very specific ones where even minor URL changes fixed the problem. And the only thing I was getting was a colon : in the console. In the end I realized that AdBlockPlus was blocking at least one these requests from going through (the request had 'Banners' in the URL).
So I'm not sure if this would have solved your problem, but I've encountered it multiple times.
using Firebug, the issue turned out to be
Blocked loading mixed active content
I had the same error on a CORS POST request.
I'm using https://cors-anywhere.herokuapp.com/ to bypass the Same-origin policy.
The problem was NoScript blocking the external domain, so in case you're using an external API in your request, this might solve it.
Same as this answer, however the problem for me isn't present neither with AdBlock nor with uBlock.
It's present with uMatrix.
You can find that it blocks the request at this URL:
chrome://umatrix/content/logger-ui.html
You can enable it manually when clicking on that field:
and choosing to enable XHR in the uMatrix popup:
The blocking persists even if you have the code packaged in an Add-on that's correctly installed (the blue bar containts Internal UUID of a Firefox Add-on), therefore if you've ever wondered why some Add-ons don't work while uMatrix (or likes) is enabled, this might be one of the reasons.

How to prevent Safari from intercepting 401 responses to ajax requests

I'm having the following problem in a Safari extension. I ask the user to provide their username/password for a web service and send off a quick request to verify that the credentials are correct. If they are not, the service will respond with a 401 as I believe it should. The problem is that Safari seems to intercept this response before my javascript code can handle it, showing the grey login box instead of letting me handle the error.
Is there anything I can do about this? I'm using a js library to make the call, but it's functionally equivalent to the following jQuery.
$.ajax({
type: "GET",
url: url,
username: username,
password: password,
success: function() { /* handle success */ },
error: function() { /* handle error */ }
});
As far as I'm aware (after having had this issue myself) there's no way you'll get Safari to stop intercepting a 401. If those findings are correct, the only way is creative (read: mis-) use of another error code, e.g. 403, or using a custom one (see below).
Of course, this assumes that you have access to changing the status code sent back from the web service (it's not entirely clear from the question if you developed the web service too).
403, of course, really says "you're already authenticated, but not authorized to access this resource", which isn't correct (hence "misuse"), but at least it has no side effects in browsers that I'm aware of.
400 is sometimes used as an alternative, but since that one ("bad request") is really meant to signify a HTTP protocol error, it may cause side effects (never seen or heard of it happening, but potentially, it might cause an over-helpful attempt by some future browser or anti-hijacking software to start troubleshooting/diagnostics).
412 is another alternative that I've seen used ("precondition failed"), but it actually is meant to indicate that the server didn't live up to the preconditions the request set.
Or you could make up your own non-standard 4xx error - e.g. 461 - which is allowed (notice that twitter has a custom 420 status code, for example)
A more correct approach would be to continue to use 401 as the error code but not send the WWW-Authenticate header when the credentials have been sent but they were not correct.
That no longer triggers the browser's dialog and allows you to process 401 directly.

Categories