1
I am making a program that needs to read the source code of a javascript file. I was trying to get the javascript file via Xmlhttprequest and return the this.responseText
, however, its value is undefined
.
How do I return the content of a javascript file in string form (without jQuery or preferably without the use of third-party libraries)?
Follow the code below
function getScriptStr(filepath) {
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
return this.responseText.split('\n');
}
};
http.open("GET", filepath, true);
http.send();
};
Rename the file you want to import from ". js" to ". txt"
– Seu Madruga
@inovapixel can not, the goal is exactly it read javascript files
– Gabriel C.
Xmlhttprequest does not execute the code... The code returned is a text/json, text/Plain or other MIME. You cannot simply include your file in the HTML document?
– Seu Madruga
You shouldn’t have much trouble doing that, but to a limitation. If the JS file is not on your server you may not have access to make this request. Anyway, put your code here so we can help. Hug
– Luciano Meireles
@inovapixel I know it doesn’t run, however I don’t understand why it returns Undefined if the file is found
– Gabriel C.
Because Xmlhttprequest returns plain text, not the file itself. If you could return ". js", would be only the text that is contained in it, so it makes it either ". txt" or ". js"
– Seu Madruga
@inovapixel yes, but for me is returning Undefined.
– Gabriel C.
Dude, but whatever, it won’t do you any good to get the ". js". I think it returns "Undefined" for ". js" files not being accepted by XHR. I’m not sure, but I don’t think they’re accepted, no.
– Seu Madruga
@Gabrielc. here on the site we do not put the question as answered, you either mark an answer as correct or answer your own question and mark as correct.
– Jorge B.
@inovapixel All right, I’ve solved the problem =)
– Gabriel C.
@Jorgeb. sorry, I’m new to the site. I think I’ll answer my own question then.
– Gabriel C.
@Gabrielc. in the good, nobody born taught. And welcome to the site :)
– Jorge B.
@inovapixel XHR accepts js files
– Denis Rudnei de Souza
@Denisrudneidesouza I got it. As I said, I wasn’t sure, it was just a hunch for returning the "Undefined".
– Seu Madruga
Also not sure, I did some tests here to confirm, the only mistake I had was CORS, but otherwise I managed to get any content by XHR
– Denis Rudnei de Souza