XMLHttpRequest responseText is always empty in Firefox WebExtension - javascript

I have a problem while writing a Firefox WebExtension add-on. The following code doesn't return any data (responseText is empty), even when the request status equals 4. In Chrome, everything is working perfectly.
I checked even on Fiddler and I can see the request is processed (and we got a response) but it looks Firefox cannot read it?
var xhr = new XMLHttpRequest();
xhr.open('GET', "http://pi.com//", true);
xhr.withCredentials = true;
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(null);
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
};
I really have no clue why Firefox is not getting the responseText filled. I already checked it with different websites, but everywhere it's the same.

In your manifest.json try adding the key "permissions": ["http://pi.com/"]

I was dealing with exactly the same problem, when porting my extension from Chrome to Firefox, it was driving me crazy!
In my case it was as simple as the mailformed URL.
Instead of http://example.com/ I had to state http://www.example.com/

Related

XmlHttpRequest.onload not working in Edge browser

I'm running into an issue where Microsoft Edge browser isn't able to execute XmlHttpRequest.onload. But it does execute in Chrome, Firefox, and Safari.
I'm creating an XmlHttpRequest object:
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("POST", authenticateUrl, true);
xhr.setRequestHeader("X-OpenAM-Username", email);
xhr.setRequestHeader("X-OpenAM-Password", password);
xhr.setRequestHeader("Content-Type", "application/json");
alert("XHR object is created");
xhr.onload = function () {
alert("start onload...");
//...receives response from service...
}
xhr.send();
The alerts in place to validate it's reaching a specific line of code. After the XMLHttpRequest object is created, the code goes into the onload function. Microsoft Edge won't go into it. As I said, Chrome, Firefox, and Safari execute this code fine.
Is there something additional needed for making Microsoft Edge run this code?
The onload function shouldn't be called until you send the XHR and the response comes back (unless there is an error). Are you calling xhr.send()?
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload
Place the xhr.responseType = "json" line after the xhr.open(...)
Because the xhr.responseType is not allowed for synchronous requests which is determined by the third parameter in the open() call.
Wait, that was in IE11, i've tried your snippet in Edge and it ran just fine.
Try adding a
xhr.onerror = err => alert('Error:' + err.message);
to see if an error occurred.

Native ajax call does not redirect on 302

I have been googling for hours now. I've read a dozen "answers" on Stackoverflow, all of them using jQuery.
This is the common answer...
The ajax-request will follow that redirect afaik
Well, it doesn't.
I am trying to send a PUT from a form via native JS AJAX
[Please I beg you, don't tell me to use jQuery. I found a bug in jQuery via PUT
(1) so I'm going around it]
This is my code snippet...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
This block works great, I can POST, PUT and DELETE without issues. The server receives the data and updates the DB according to the sent METHOD just fine.
My (SLIM based) PHP, upon successful completion, returns a 302 and a URL to go to.
This process works using POSTMAN hitting the PHP, and it goes to the right page.
Opening Chrome Tools/Network, it shows that the PHP is returning a 302 and than a 200
My response object contains the full HTML for a page in the responseText property.
Funny thing is, if I hard code a bad URL,the browser goes to my 404 page fine.
Your thoughts? (Please don't ask me or tell me to use jQuery)
EDIT/ADDENDUM -----------------------
I have discovered that the redirect is using the same METHOD of the original call.
I'm doing
PUT /user/1
the Redirect is doing
PUT http://myserver.test/
This is the right place to go. Now I understand the 405.
I don't have a PUT route defined, therefore the 405.
I create a PUT route and it works in POSTMAN but still gives me a 405 in Chrome and Firefox.
I have 2 issues to solve:
1) change the METHOD on the redirect
2) figure out why the browser doesn't like the 307
I found "a" solution. I'm not sure I like it, but...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
window.location.replace(xhr.responseURL); // <---- solution
}
};

Ajax Call empty response on Google chrome Mobile

i searched for an answer that fix my problem a lot, but none of the topic fit my scenario..
I have to make an AJAX call inside my application, it work fine on ALL desktop browser, and on SOME mobile browser (for example on my ASUS zenPhone native browser it work correctly, even on my iPhone from work (FF and Safari)) but no way in google Chrome (mobile), in this one the call complete but the response it's empty (only empty, no error provided)... i ask some friend to test it too and similar result occours (empty response) .... i have an https server and an https endpoint
there is my code:
<script>
var x = Math.floor((Math.random() * 10000000) + 2000);
var data = JSON.stringify({
"Token": x,
"Subject": "testAPI"
});
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
//console.log(this.responseText);
var dataJ = JSON.parse(this.responseText);
var dataA = dataJ.Questions;
alert(dataA[0].img);//this is already empty on my mobile :(
dataA.forEach(function(entry) {
//console.log(entry);
});
}
});
xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
</script>
Server side CORS are enabled, and as i said it works flawless on all desktop i tested on ... i don't know if i can provide the url to you guys(i have to ask # the API provider) but if you give me some hints it would be nice ...
thanks a lot for your time!
[EDIT]
after some trouble i get an error(Testing remotly from my phone to my PC with dev tools)
Failed to load resource: net::ERR_INSECURE_RESPONSE
on the other device i didn't get this error...
This is a long shot but, try to set the content type header to :
xhr.setRequestHeader("content-type", "text/plain");
This should suppress the CORS preflighting done by chrome which causing the empty response.

GET Method failed to return resource

I am hosting a webpage in WAMP and keep on receiving this error in the Chrome Developer Console
GET http://localhost/surveys/Internet.json survey.js:368
my survey.js line 368 is in this function`
function loadJSON(key,json){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var obj = xhr.responseText;
localStorage.setItem(key,obj);
}
}
};
xhr.open("GET", json, true);
xhr.send(); // <<-------------------------- line 368
}
I have no clue what is going on. I recently tried to reinstall wamp hoping it was just a conflict with another application but it did not solve anything.
Any help would be great.
It was a problem in the CACHE MANIFEST file
It must be noted in the manifest that these files need internet connection to become available which in my case I did not.
CACHE MANIFEST
#Files to store on application cache
NETWORK
#Files that would require internet connection to access

XMLHttpRequest receiving no data or just "undefined"

i try to make a Firefox Addon which runs a XMLHttp Request in Javascript. I want to get the data from this request and send it to *.body.innerhtml.
That's my code so far...
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://xx.xxxxx.com", true);
xhr.send();
setTimeout(function() { set_body(xhr.responseHtml); }, 6000);
Instead of receiving the data, I get "undefined". If I change xhr.responseHtml to responseText I get nothing. I don't know why I'm getting nothing. I'm working on Ubuntu 12.04 LTS with Firefox 12.0.
If you need any more details on the script please ask!
Update:
set_body Function
document.body.innerHTML = '';
document.body.innerHTML = body;
document.close();
Update SOLVED:
I had to determine the RequestHeaders (right after xhr.open):
xhr.setRequestHeader("Host", "xxx");
For following Items: Host, Origin and Referer. So it seems there was really a problem with the same origin policy.
But now it works! Thanks to all!
when you set the last param of open to true you are asking for an async event. So you need to add a callback to xhr like so:
xhr.onReadyStateChange = function(){
// define what you want to happen when server returns
}
that is invoked when the server responds. To test this without async set the third param to false. Then send() will block and wait there until the response comes back. Setting an arbitrary timeout of 6 seconds is not the right way to handle this.
This code should work:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
set_body(xhr.responseText);
}
};
xhr.open("GET", "http://xx.xxxxx.com", true);
xhr.send();
Make sure that you are getting a correct response from URL http://xx.xxxxx.com. You may have a problem with cross-domain calls. If you have a page at domain http://first.com and you try to do XMLHttpRequest from domain http://second.com, Firefox will fail silently (there will be no error message, no response, nothing). This is a security measure to prevent XSS (Cross-site scripting).
Anyway, if you do XMLHttpRequest from a chrome:// protocol, it is considered secure and it will work. So make sure you use this code and make the requests from your addon, not from your localhost or something like that.

Categories

Resources