Is it possible to have Chrome write the console output to a local file?
If not; Can I make an external call from the console to my server and save it there?
I know this can be done with devtool extended but I would rather do it from console.
You can't write into a file in a local computer. It will lead to great security flaw.
Best way is to save the data in server.
The following may work, but need some server side work.
(function(console){
var url = "domain.com/../userdata/"
console.save = function(data, filename){
var ajaxreq = new XMLHttpRequest();
ajaxreq.open("POST", url+filename, false);
ajaxreq.onreadystatechange = function ()
{
if(ajaxreq.readyState === 4)
{
if(ajaxreq.status === 200)
{
alert(ajaxreq.responseText);
}
}
}
ajaxreq.send(data);
}
})(console);
Related
I have encountered a problem with my Java script/jQuery code.
I want to make a piece of code which could fulfill the following requirement:
1.Make the browser save my remote binary file, let's say http://192.168.0.100/system/diagdata
2.Since the preparing the file in the server side with cost some time(usually around 40s), so I need a callback to let me know when the data will be ready to download(the file itself is very small, so let's ignore the actually data transmit duration) so that I could display some kind of loading page to tell the user the downloading procedure is on the way.
At first, I make a piece of code like this without callback:
var elemIF = document.createElement("iframe");
elemIF.src = 'http://192.168.0.100/system/diagdata';
elemIF.style.display = "none";
document.body.appendChild(elemIF);
It works well(but without callback)
Then in order to make callback possible, then I added some code like this:
var deferred = jQuery.Deferred();
var elemIF = document.createElement("iframe");
elemIF.src = 'http://192.168.0.100/system/diagdata';
elemIF.style.display = "none";
document.body.appendChild(elemIF);
elemIF.defer = 'defer';
if (window.ActiveXObject) { // IE
sc.onreadystatechange = function() {
if ((that.readyState == 'loaded'
||that.readyState == 'complete') ) {
}
}
}
else { // Chrome, Safari, Firefox
elemIF.onload = function() {
alert("onload");
};
elemIF.onerror = function(e) {
alert("onerror");
};
}
deferred.promise();
After I run this piece of code, the "onload" has been called, but the browser did not tend to save the file "diagdata" but try to load it and report a parsing error exception.
Did anyone have a substitute solution which could not only make browser save the binary file but also will callback to inform the data ready status?
First off, I am very new to web services, web workers, and XMLHttpRequests, so please bear with me. Also, there are a lot of stipulations in my project, so solutions to "just do it this way" may not be viable.
So I have a web service set up to receive calls from an XMLHttpRequest in javascript, and it does this synchronously. This works fine, but it ties up the UI thread, and I would like to have a loading spinner run while making the requests to the server. Due to one issue, I can't have the program access external scripts on the web, so I am using a Blob to mask the "file://" preface.
I am also using an inline webworker to accomplish this. Now I'm getting to my actual issue. Spawning the webworker is fine, and I can create and send the XMLHttpRequest, but as soon as I call "send" everything exits. It will run no lines of code after this.
Here's some code:
Called from JS:
var blob = new Blob([document.querySelector('#getWorker').textContent]);
var blobUrl = window.URL.createObjectURL(blob);
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function (e) {
alert(e.data);
}
worker.postMessage();
The worker:
var bigString = "";
var invocation = new XMLHttpRequest();
var url = 'http://<ipAddress>/<serviceName>/Service.asmx/<method>';
if (invocation) {
invocation.open('GET', url, false);
invocation.send(); //*****EXITS AFTER THIS LINE*****//
if (invocation.status == 200) {
var responseText = invocation.responseText.replace(/(\r\n|\n|\r)/gm, "");
responseText = responseText.replace('<?xml version="1.0" encoding="utf-8"?>', '');
responseText = responseText.replace('<string xmlns="http://tempuri.org/">', '');
responseText = responseText.replace('</string>', '');
postMessage("Success");
//updateTable(responseText);
} else {
postMessage("Fail");
//alert("Could not connect to database. Check your internet connection.");
}
var c = 0;
var b = 1;
}
var q=1;
The debugger will just end after the "invocation.send()" line. No error, no status, no nothing. And that's where I'm lost.
Any insight would be greatly appreciated. Also, this exact code works when it is not in a WebWorker, so there's likely something about them that I do not understand.
Thanks in advance!
Chrome problem. Silent fail if COR request is blocked. Firefox console shows more information on the error.
I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:
<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
and (with file_inhoud, lines defined elsewhere)
function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
Debug function shows:
readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
So statement that stops the program is:
var file_inhoud=doc.document.body;
What is wrong? What is correct (or best) way to read this file?
Note: I see that the file is read and displayed in the frame.
Thanks!
Your best bet, since the file is on your server is to retrieve it via "ajax". This stands for Asynchronous JavaScript And XML, but the XML part is completely optional, it can be used with all sorts of content types (including plain text). (For that matter, the asynchronous part is optional as well, but it's best to stick with that.)
Here's a basic example of requesting text file data using ajax:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
You'd call that like this:
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
However, the above is somewhat simplified. It would work with modern browsers, but not some older ones, where you have to work around some issues.
Update: You said in a comment below that you're using jQuery. If so, you can use its ajax function and get the benefit of jQuery's workarounds for some browser inconsistencies:
$.ajax({
type: "GET",
url: "path/to/file",
success: function(text) {
// `text` is the file text
},
error: function() {
// An error occurred
}
});
Side note:
I found that javascript is client based...
No. This is a myth. JavaScript is just a programming language. It can be used in browsers, on servers, on your workstation, etc. In fact, JavaScript was originally developed for server-side use.
These days, the most common use (and your use-case) is indeed in web browsers, client-side, but JavaScript is not limited to the client in the general case. And it's having a major resurgence on the server and elsewhere, in fact.
The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.
I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
How can I get the contains of this JSON file in an object in JavaScript?
This is for example my JSON file located at ../json/main.json:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
and i want to use it in my table.js file like this:
for (var i in mainStore)
{
document.write('<tr class="columnHeaders">');
document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
document.write('<td >'+ mainStore[i]['description'] + '</td>');
document.write('</tr>');
}
Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...
Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.
If he can't properly profile native VS jQuery, he shouldn't even be programming native code.
Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...
JSON has nothing to do with jQuery.
There is nothing wrong with the code you have now.
To store the variable mainStore, it is a variable in that json.
You should store that json to a variable:
var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};
var mainStore = myJSON.mainStore;
//.. rest of your code.
I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.
If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
}
};
xhttp.open("GET", "./user.json");
xhttp.send();
}
Naming using the linux filename structure
You can store the responseText to a variable or whatever you want to do with it
On the server, there is a text file. Using JavaScript on the client, I want to be able to read this file and process it. The format of the file on the server cannot be changed.
How can I get the contents of the file into JavaScript variables, so I can do this processing? The size of the file can be up to 3.5 MB, but it could easily be processed in chunks of, say, 100 lines (1 line is 50-100 chars).
None of the contents of the file should be visible to the user; he will see the results of the processing of the data in the file.
You can use hidden frame, load the file in there and parse its contents.
HTML:
<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>
JavaScript:
<script type="text/javascript">
function LoadFile() {
var oFrame = document.getElementById("frmFile");
var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
while (strRawContents.indexOf("\r") >= 0)
strRawContents = strRawContents.replace("\r", "");
var arrLines = strRawContents.split("\n");
alert("File " + oFrame.src + " has " + arrLines.length + " lines");
for (var i = 0; i < arrLines.length; i++) {
var curLine = arrLines[i];
alert("Line #" + (i + 1) + " is: '" + curLine + "'");
}
}
</script>
Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.
Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax() function.
<html><head>
<script src="jquery.js"></script>
<script>
getTxt = function (){
$.ajax({
url:'text.txt',
success: function (data){
//parse your data here
//you can split into lines using data.split('\n')
//an use regex functions to effectively parse it
}
});
}
</script>
</head><body>
<button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button>
</body></html>
You need to use Ajax, which is basically sending a request to the server, then getting a JSON object, which you convert to a JavaScript object.
Check this:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
If you are using jQuery library, it can be even easier:
http://api.jquery.com/jQuery.ajax/
Having said this, I highly recommend you don't download a file of 3.5MB into JS! It is not a good idea. Do the processing on your server, then return the data after processing. Then if you want to get a new data, send a new Ajax request, process the request on server, then return the new data.
Hope that helps.
I used Rafid's suggestion of using AJAX.
This worked for me:
var url = "http://www.example.com/file.json";
var jsonFile = new XMLHttpRequest();
jsonFile.open("GET",url,true);
jsonFile.send();
jsonFile.onreadystatechange = function() {
if (jsonFile.readyState== 4 && jsonFile.status == 200) {
document.getElementById("id-of-element").innerHTML = jsonFile.responseText;
}
}
I basically(almost literally) copied this code from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2 so credit to them for everything.
I dont have much knowledge of how this works but you don't have to know how your brakes work to use them ;)
Hope this helps!
It looks like XMLHttpRequest has been replaced by the Fetch API. Google published a good introduction that includes this example doing what you want:
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
However, you probably want to call response.text() instead of response.json().
Just a small point, I see some of the answers using innerhtml. I have toyed with a similar idea but decided not too, In the latest version react version the same process is now called dangerouslyinnerhtml, as you are giving your client a way into your OS by presenting html in the app. This could lead to various attacks as well as SQL injection attempts
You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status and if it is from web server it returns the status)
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
For device file readuing use this:
readTextFile("file:///C:/your/path/to/file.txt");
For file reading from server use:
readTextFile("http://test/file.txt");
I really think your going about this in the wrong manner. Trying to download and parse a +3Mb text file is complete insanity. Why not parse the file on the server side, storing the results viva an ORM to a database(your choice, SQL is good but it also depends on the content key-value data works better on something like CouchDB) then use ajax to parse data on the client end.
Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.