Reputation: 57
I using add-on builder build an addon with basic functions:
- get comments (A) from page http://youtube.com
.
- Call the web server process this text (A) and return json
- replace (A) by (B) and show it for user
I got problem with request to server (see in Browser console have many line ) :
GET http://localhost:8084/Test/Test [HTTP/1.1 200 OK 8ms]
JSON.parse unexpected end of data fire fox addon.
But last request is success. And my code do not change comment because it changed before request response.
lib/main.js
var tag = "p";
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "*.youtube.com",
contentScriptFile: data.url("element-getter.js"),
contentScriptWhen: "end"
});
data/element-getter.js
var target = document.querySelector('#watch-discussion');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var commenttexts = document.querySelectorAll(".comment-text");
for (var i = 0; i < commenttexts.length; ++i) {
var url = "http://localhost:8084/Test/Test";
var request = new XMLHttpRequest();
var cm = " hello ";
request.open("GET", url, true);
request.onload = function () {
var jsonResponse = JSON.parse(request.responseText);
var status = jsonResponse.status;
cm = status;
};
request.send();
commenttexts[i].innerHTML = cm;
}
});
});
var config = { childList: true };
observer.observe(target, config);
json server return:
{"status":"1","label":"true"}
Upvotes: 1
Views: 299
Reputation: 21657
You are creating an assynchronous request, so thist part:
commenttexts[i].innerHTML = cm;
should be called when the request responds, i.e. inside the request.onload function, not after the request.send();
. Having it at the end, means it will run first that part, before the request comes back.
You should have something like this:
for (var i = 0; i < commenttexts.length; ++i) {
(function(i) {
var request = new XMLHttpRequest();
var cm = " hello ";
request.open("GET", url, true);
request.onload = function () {
var jsonResponse = JSON.parse(request.responseText);
var status = jsonResponse.status;
cm = status;
commenttexts[i].innerHTML = cm;
};
request.send();
})(i);
}
This way it only gets changed when it comes back, and you have access to the i variable inside the onload function.
Upvotes: 1