I'm using XMLHttpRequest to read a text file (on local) after a period of time (after 10s).
After 10s, XMLHttpRequest retrieves the text file but the content (responseText) does not changed even though I have changed it.
Here is my code:
var list = [];
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText.length == 0) {
undef();
}
else {
def();
}
}
}
getFile();
function getFile() {
list = [];
xhr.open("GET", chrome.extension.getURL('text/list.txt'), true);
xhr.send(null);
}
var myVar = setInterval(function(){getFile()}, 10 * 1000);
function def() {
// do something
}
function undef() {
// do something
}
I don' know why and how to fix it, please help.
The fast/lazy solution is to change your link address without changing the file it's accessing.
Modify your link with LinkToFile+"?="+Math.random()
It won't match anything in the cache but it will fetch the same file.
I found the problem, it is that the folder containing the file that I use when coding is different from the folder containing the extension when added to Chrome.
I just modified the wrong file.
Thank you everyone for your help.
Related
I'm trying to write a VSTS extension that needs to load (and parse) a JSON file but I'm having a hard time finding the right way to do it.
So I have something like:
VSS.init({
explicitNotifyLoaded: true,
usePlatformScripts: true
});
var witClient;
var rules;
VSS.ready(function () {
require(["fs"], function (fs) {
rules = JSON.parse(fs.readFileSync("urlMatches.json"));
})
VSS.require(["VSS/Service", "TFS/WorkItemTracking/RestClient"], function (VSS_Service, TFS_Wit_WebApi) {
// Get the REST client
witClient = VSS_Service.getCollectionClient(TFS_Wit_WebApi.WorkItemTrackingHttpClient);
});
// Register a listener for the work item page contribution.
VSS.register(VSS.getContribution().id, function () {
return {
// Called after the work item has been saved
onSaved: function (args) {
witClient.getWorkItem(args.id).then(
function (workItem) {
// do some stuff involving the loaded JSON file...
});
}
}
});
VSS.notifyLoadSucceeded();
});
I've tried a bunch of variations on this without any luck. I've even tried using jQuery to load my file synchronously and yet my rules ends up undefined.
So I have the file urlmatches.json and I need to load it and use it to populate the variable rules before I get to the onSaved handler.
You can retrieve content through HTTP request, for example:
onSaved: function (args) {
console.log("onSaved -" + JSON.stringify(args));
var request = new XMLHttpRequest();
request.open('GET', 'TestData.txt', true);
request.send(null);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader('Content-Type');
console.log(request.responseText);
}
}
I am trying to write templates for a mobile app, as I only know pure JavaScript, so my plan is replacing the default template with a new one. After few hours I was nearly exhausted on this issue. It is not CORS thing and all the files are in localhost.
function getTheme(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "model/1/index.html", true);
xhr.responseType = "document";
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0) {
var customTheme = document.getElementById('crapDiv');
customTheme.innerHTML = xhr.responseXML;
}
}
}
xhr.send(null);
}
This Ajax works quite fine when I test with a text file, but as MDN said, to retrieve a html with ajax, a "document" responseType must be declared, thus, with the xhr.responseXML it only returns a DOM object, which is [object HTMLDocument]
I just can not parse this object back into contents so that I could not insert it into another html file.
So, How could I get through with this issue plz? and, plz only pure JS code.
You can't edit a file's content with JavaScripts, you can only read it. It's not for that. You need a server with eg PHP that can save your data.
You can get the response data as raw text with xhr.responseText.
Finally I got it.
function getTheme(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "model/1/index.html", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0) {
var customTheme = document.getElementById('crapDiv');
customTheme.innerHTML = xhr.responseText;
}
}
}
xhr.send(null);
}
The diff is just the declare of the responseType, by default it is "", and xhr.responseText is the right way to retrieve the content, while the xhr.responseXML is the right way to retrieve the DOM object.
As it should be xhr.responseText, so there is no more need to declare responseType, and must be "" or "Text" if you still want a decalration.
Thnx.
I use the code below to get a web page(html)
var htmlString=null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.yahoo.com");//can change to any web address
xhr.onreadystatechange = function() {
htmlString=htmlString+xhr.responseText;
if(xhr.statusText=="200 OK\r" ){
log (global.htmlString.length);
}
}
but it always get one part of the page, rather than whole html code
Is there any parameter to set the length of the return html code?
Your comment welcome
There will be multiple readystatechange events. The request will only be completely done when xhr.readyState === XMLHttpRequest.DONE === 4.
Also, htmlString = null; ...; htmlString=htmlString+xhr.responseText; is bogus in many ways. First time around it will do htmlString = null + "text" === "nulltext. Afterwards it will add .responseText (as retrieved so far) again and again, while going through the states.
Also, on a related note, you should check xhr.status == 200, not xhr.statusText == randomString. Web servers aren't necessarily sending "OK" in case of 200.
Read the XMLHttpRequest documentation.
Something like this should work better:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.yahoo.com");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 /* DONE */) {
console.log(xhr.responseText.length);
// Do something with it...
}
}
xhr.send();
I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.
UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:
var materialFilename;
function loadOBJModel(filename)
{
// ...
var req = new XMLHttpRequest();
req.open('GET', filename);
req.responseType = 'text';
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line)
{
readLine(line);
});
}
}
req.send();
alert(materialFilename);
// ...
}
function readLine(line)
{
// ...
else if (tokens[0] == "mtllib")
{
materialFilename = tokens[1];
}
// ...
}
You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.
To scan line-by-line, you can use split(). E.g. Something like this ...
var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line, i) {
// 'line' is a line of your file, 'i' is the line number (starting at 0)
});
} else {
// (something went wrong with the request)
}
}
}
req.send();
If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.
You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.
Once you have the data, parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for that out of the box.
I'd like to refer to the version number as defined in my manifest.json in my extension's JavaScript files.
Is there any way to do this?
Since chrome 22 you should use chrome.runtime.getManifest(). See docs here.
So now it is as simple as:
var manifest = chrome.runtime.getManifest();
console.log(manifest.name);
console.log(manifest.version);
I think that this is what you're looking for http://www.martinsikora.com/accessing-manifest-json-in-a-google-chrome-extension
chrome.manifest = (function() {
var manifestObject = false;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
manifestObject = JSON.parse(xhr.responseText);
}
};
xhr.open("GET", chrome.extension.getURL('/manifest.json'), false);
try {
xhr.send();
} catch(e) {
console.log('Couldn\'t load manifest.json');
}
return manifestObject;
})();
And that's all. This short code snippet loads manifest object and put's it among other chrome.* APIs. So, now you can get any information you want:
// current version
chrome.manifest.version
// default locale
chrome.manifest.default_locale