Not enough arguments to XMLHttpRequest.open - javascript

I am using AJAX2 as described here
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
to monitor progress of ajax request, but i am receiving following error "TypeError: Not enough arguments to XMLHttpRequest.open."
Can anyone help why this error occuring?
My Code is:
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress);
oReq.addEventListener("load", transferComplete);
oReq.addEventListener("error", transferFailed);
oReq.addEventListener("abort", transferCanceled);
oReq.open();
// ...
// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
console.log(percentComplete+ " percent completed.");
// ...
} else {
console.log(" Unable to compute progress information since the total size is unknown.");
// Unable to compute progress information since the total size is unknown
}
}
function transferComplete(evt) {
console.log("The transfer is complete.");
}
function transferFailed(evt) {
console.log("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
console.log("The transfer has been canceled by the user.");
}
Actuall error is occuring on this line
oReq.open();

open() method has three parameters
open('get' , url , true or false or null)

The code example in that document is not complete, working code. It is designed to show you how to add progress tracking to existing, working XMLHttpRequest code.
You need to fill in the gaps yourself (or better yet: Build a basic XHR based script and then add the progress tracking to it). That includes replacing:
oReq.open();
with a real call to open. See the documentation for open. At a minimum you need to provide an HTTP method and a URL (both string arguments).

Related

How to catch silent NS_ERROR_OUT_OF_MEMORY in Chrome

I tested the loading of very large files with XMLHttpRequest and noticed an interesting behavior of Chrome (90.0.4430.212): It loads the full file, but finishes with a 200-OK code and and empty (!) result. First I thought it was a silent timeout or whatever, but no, it seems to be a reached memory limit.
Trying it in Firefox (13.0esr (64-bit)) took for ages, but in the end I knew more: The Transfer itself did not trigger an "error" or a "timeout" event, resulted with 200 and empty result as well. But it threw an error:
Exception { name: "NS_ERROR_OUT_OF_MEMORY", message: "", result: 2147942414, filename: "http://localhost/testcenter-backend/vo_data/teterei.html", lineNumber: 16, columnNumber: 0, data: null, stack: "transferComplete#http://localhost/testcenter-backend/vo_data/teterei.html:16:9\n" }
So it has nothing to do with the transport itself, but apparently a memory limit reached when trying to do anything with the result. When I don't use the oReq.response, the error does not appear.
Okay, how to handle this? In Firefox I can catch the error with a simple try catch block. But this does not work for Chrome. A naive approach would be just to check if the resulting content is empty, but I wonder if there is another possibility to detect this stuff happening.
--
How to reproduce:
Create a huge file.
I generated a 10,4GB file this way:
dd if=/dev/zero of=test.img bs=1024 count=0 seek=$[1024*10000]
Run this code in a browser to load it.
const oReq = new XMLHttpRequest();
function updateProgress (oEvent) {
console.log("progress", oEvent.loaded);
}
function transferComplete(evt) {
console.log("The transfer is complete.", oReq.getAllResponseHeaders(), oReq.status);
console.log(oReq.response); // here too much memory is allocated
}
function transferFailed(evt) {
console.log("error", oReq.getAllResponseHeaders(), oReq.status);
}
function transferCanceled(evt) {
console.log("cancel", oReq.getAllResponseHeaders(), oReq.status);
}
function timeOut(evt) {
console.log("timeout", oReq.getAllResponseHeaders(), oReq.status);
}
oReq.addEventListener("progress", updateProgress);
oReq.addEventListener("load", transferComplete);
oReq.addEventListener("error", transferFailed);
oReq.addEventListener("abort", transferCanceled);
oReq.addEventListener("timeout", timeOut);
// your huge file here instead
oReq.open("GET", "https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"); // URL to huge file here
oReq.send();
The actual memory limit may vary to your system.

Is it possible to get web-page loading elements progress in percentage?

When a web page starts loading for the first time browser download images, javascript, CSS and other assets. I want to measure this loading progress by (%) notations.
To do this script I have explored JavaScript's window.onload but I didn't get any properties & methods as required.
function load() {
var preload = document.querySelector('#magic-box');
preload.style.display="none";
}
window.onload = load;
window.onload pretty enough for creating a simple preloader for the webpage. In the GitHub & Codepen there are a lot of percentage preloaders. But they are not calculating the absolute percent, They are modified & static. If we can measure webpages elements loading progress we can make an awsome & cool preloader
Check your average latency then use that time for loading percentage. After that time set your state to loaded
Tracking progress of entire page can be problematic, but tracking a specific resource can be tracked. An xhr request have onprogress event. In which you can get total length of the response and currently loaded content.
As an example from this site
let xhr = new XMLHttpRequest();
// 2. Configure it: GET-request for the URL /article/.../load
xhr.open('GET', '/article/xmlhttprequest/example/load');
// 3. Send the request over the network
xhr.send();
// 4. This will be called after the response is received
xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP status of the response
alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
} else { // show the result
alert(`Done, got ${xhr.response.length} bytes`); // responseText is the server
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
console.log(`Received ${event.loaded} of ${event.total} bytes progress -> ${(event.loaded/event.total * 100)}%`);
} else {
console.log(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function() {
alert("Request failed");
};
xhr.onprogress is the part where progress can be tracked.

iMacros and socket.io

In my iMacros script I try to connect to a server using socket.io.
First I have to obtain the socket.io.js file, evaluate it and then use socket.io as normal.
Here is an excerpt from my script:
function loadScriptFromURL(url) {
try {
var request = Components.classes['#mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Components.interfaces.nsIXMLHttpRequest);
request.open('GET', url, false);
request.send();
if (request.status !== 200) {
var message = 'There was an error trying to connect to: ' + url + ', request status: ' + request.status;
iimDisplay(message);
}
eval(request.response);
} catch (e) {
window.console.log(e);
return false;
}
return true;
//alert(request.respsonse);
}
loadScriptFromURL('http://localhost:3700/socket.io/socket.io.js');
window.console.log(io.version); // returns 0.9.16
var socket = io.connect('http://localhost:3700');
The problem is that a Javascript code that is executed by iMacros is in the scope of the plugin (a sandbox), and when I use the io's connect method I get the "io.util is undefined" error.
Is there a way to populate this method so that iMacros could see it? I guess I need to make some changes in the socket.io.js file, but not quite sure yet...
I spent a couple of days to find a solution. I have another errors, for example "setTimeout() is not a function, Blob is not a function, diferent undefined errors..."
This occurs because the code is not running in the context of the current window.
Solution:
Go to "/node_modules/socket.io-client\socket.io.js"
It's client javascript code from url "http://localhost:3000/socket.io/socket.io.js"
Replace all:
"new Blob" -> "new window.Blob"
"instanceof Blob" -> "instanceof window.Blob"
And to do the same for:
Filereader - > window.Filereader
setTimeout() - > window.setTimeout()
clearTimeout() - > window.clearTimeout()
setTimeout() - > window.setTimeout()
It's working for me. Node.JS version is 5.3.0, Socket.IO version is 1.4.5.

try catch doesn't work with sse

This is the code, P.S: the service httpd in s10 is stopped
try {
var source = new EventSource("http://s10/server.php");
console.log(source);
} catch (e) {
console.log("ADSfasfasfasdfasdfas" + e)
}
this is the console:
why the heck the try catch is not catching the error ??
ofcourse I have onerror event and onclose event:
source.addEventListener('error', function(e) {
if (source.readyState == 2) {
connectionClosed();//to change some style
console.log("Disconnected");
}
}, false);
source.onerror = function(e) {
if (source.readyState != 0) {
connectionClosed();//to change some style
console.log("Disconnected");
}
};
source.onclose = function() {
connectionClosed();//to change some style
console.log('Connection closed');
}
When I run this in the Console on an arbitrary URL that isn't set up to handle SourceEvents, the Console successfully logs a SourceEvent instance. This is similar to what you're describing.
So my guess here is that there's no error to catch. The SourceEvent instance is successfully constructed, even though there's no actual connection. If you want to detect if the connection is working, use the EventSource.readyState property.
In my screenshot you can see that readyState = 0, which means that the connection is "connecting", but in reality it's never going to finish connecting because the server on the other side isn't set up to handle SourceEvents.
https://developer.mozilla.org/en-US/docs/Web/API/EventSource/readyState
I'm testing the same thing, the onerror doesn't provide really useful info. For example, if you shut down your server or if you send an empty response while your client is connected, you can't detect programmatically on the client side the specific cause, I can see that just inspecting the dev console.

Catching same origin exception in Javascript?

I'm trying to create my own XMLHttpRequest framework to learn how this things work internally.
A thing that puzzles me is that I cannot find how to catch a "Same origin" exception.
The idea behind this is that I try to load a URL, if I get a Same origin exception, I re-request the URL through a proxy script local for the script. The reason I do this is because I need to access production data from a development sandbox and I want it to be as transparent as possible for the script itself.
I know it's a bad practice but this is the least intrusive way of doing this at the moment :)
Just to clear things - I don't want to bypass same origin, I just want to catch the thrown exception so I can do something about it.
Here is the code I currently use for my xhr:
var net = function (url, cb, setts){
this.url = url;
this.cb = cb;
var oThis = this;
if (!this.xhr) {
this.xhr = new XMLHttpRequest();
this.xhr.onreadystatechange = function() {
if (oThis.xhr.readyState == 4 && oThis.xhr.status == 200) {
document.body.innerHTML += "RS: "+oThis.xhr.readyState+"; ST:"+oThis.xhr.status+"; RP:"+oThis.xhr.responseText+"<br>";
}
else {
// do some other stuff :)
document.body.innerHTML += "RS: "+oThis.xhr.readyState+"; ST:"+oThis.xhr.status+"; RP:"+oThis.xhr.responseText+"<br>";
}
}
}
this.xhr.open("GET", url,true);
this.xhr.send();
} // It's WIP so don't be scared about the unused vars or hardcoded values :)
I've tried to try...catch around xhr.send(); but no avail, still can't catch the exceptions.
Any ideas or pointers would be greatly appreciated.
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
if (xhr.status==0) {
alert("denied");
} else {
alert("allowed");
}
}
}
Are you sure it's actually supposed to throw an exception? I can't see anything in the specifications: http://www.w3.org/TR/XMLHttpRequest/#exceptions Looks like it does. My bad.
In either case, you can always check the domain of the incoming string against the domain of the page the user is currently on.
FWIW, as you can see by this jsFiddle (open up Web Inspector), Chrome doesn't really throw an exception. It just says "Failed to load resource".

Categories