I have a page where users can add images (browse for files, drag/drop or copy/paste) from their filesystem, clipboard, or external websites. If an image fails to load, I'd like to let the user know why. For example, 404 (resource not found) or 403 (Forbidden) - users may want to try different things depending on why the image failed to load.
I'm dealing with failure using the following code:
var image=$('<img>').appendTo(container);
image.error(function(e){/* error handling code*/});
image.attr('src','example.jpg');
I can't figure out how to access the particular error code that led to failure. If I open developer tools (chrome), the error message gets displayed there... how can I access that same message in my code?
You can try this.
var img = $.get("/img/example.jpg");
var statusCode = img.status,
statusText = img.statusText;
Related
I'm making a page that has multiple iFrames that show reports. The reports generate a ton of console output which contributes to the page taking up more memory.
I tried to do the workaround with
console.log = function() {}
As well as a couple others I found, but none of them work. Majority of the errors are "Failed to load resource" and failed GET requests. I'm wondering if there's a way to maybe filter just those out.
Again the issue is that all the iFrames are cross domain and I have 0 access to the source.
Failed requests and other browser errors are logged by the browser internally, not through console.log. There is no way for your page to filter them out. If you don't want to see them, don't look at the console.
Try it like this
iframeWindow.console.log = function() { /* nop */ };
This works on Mozilla,Chrome
Have an issue where an iframe with external source loads a page with errors thrown in console. What i'm looking for is a solution to grab these errors and determine what information to show based on them. There are multiple iframes loading within the page.
So, the code outside the iframe should track and collect the console info. How can I achieve this? Thanks!
Just an example I get this error in console:
Refused to display 'http://[url]/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
I would like to catch this error and infrom user that the webpage could not load properly.
If you have an access to iframe's code, you can actually post messages to window.parent depending on errors and handle them on your side. Take a look at that at Mozilla's window.postMessage
Just say I typed in a bad hostname in the address bar.
For example, say I wasn't running a local web server, and I load:
http://localhost/callback_url
In Chrome, this will give me a "This webpage is not available" message.
Is there anyway I can find out what the url is in the address bar from the Javascript console, even though the page failed to load?
I know I can normally use window.location.href to get this, but that returns "data:text/html,chromewebdata" in this instance.
So in this example, I'd like to know if there's some javascript that returns http://localohost/callback_url
EDIT: The main reason I'd like to do this is so I know if server side redirect failed when using ChromeDriver with Selenium. So I'd prefer to avoid using extensions if possible, and am open to Chrome and ChromeDriver specific solutions if applicable! The callback_url may have extra info in it, added by the server, and I'd like to see what this info is. I'd like to avoid running another server to get this data if possible.
The loadTimeData object included in the ERR_CONNECTION_REFUSED page has the failed URL:
> loadTimeData.data_.summary.failedUrl
"http://localhost/foo?request_url=bar"
You can get it from the title of the page.
By typing document.title and doing some regex you can get the URL.
Another way I found is by using the following
var data = loadTimeData.createJsEvalContext();
console.log(data.a.$top.summary.failedUrl);
If you open the developer tools and search for a part of the URL in source code, you will see that Chrome creates the loadTimeData in the "not available page".
I am using the following dirty workaround code to simulate an ajax file upload. This works fine, but when I set maxAllowedContentLength in web.config, my iframe loads 'normally' but with an error message as content:
dataAccess.submitAjaxPostFileRequest = function (completeFunction) {
$("#userProfileForm").get(0).setAttribute("action", $.acme.resource.links.editProfilePictureUrl);
var hasUploaded = false;
function uploadImageComplete() {
if (hasUploaded === true) {
return;
}
var responseObject = JSON.parse($("#upload_iframe").contents().find("pre")[0].innerText);
completeFunction(responseObject);
hasUploaded = true;
}
$("#upload_iframe").load(function() {
uploadImageComplete();
});
$("#userProfileForm")[0].submit();
};
In my Chrome console, I can see
POST http:/acmeHost:57810/Profile/UploadProfilePicture/ 404 (Not
Found)
I would much prefer to detect this error response in my code over the risky business of parsing the iframe content and guessing there was an error. For 'closer-to-homeerrors, I have code that sends a json response, but formaxAllowedContentLength`, IIS sends a 404.13 long before my code is ever hit.
There is not much you can do if you have no control over the error. If the submission target is in the same domain than the submitter and you are not limited by the SOP, you can try to access the content of the iframe and figure out if it is showing a success message or an error message. However, this is a very bad strategy.
Why an IFRAME? It is a pain.
If you want to upload files without the page flicking or transitioning, you can use the JS File API : File API File Upload - Read XMLHttpRequest in ASP.NET MVC
The support is very good: http://caniuse.com/#feat=filereader
For old browsers that does not support the File API just provide a normal form POST. Not pretty... but ok for old browsers.
UPDATE
Since there is no chance for you to use that API... Years ago I was in the same situation and the outcome was not straightforward. Basically, I created a upload ticket system where to upload a file you had to:
create a ticket from POST /newupload/ , that would return a GUID.
create an iframe to /newupload/dialog/<guid> that would show the file submission form pointing to POST /newupload/<guid>/file
serve the upload status at GET /newupload/guid/status
check from the submitter (the iframe outer container) the status of the upload every 500ms.
when upload is started, hide the iframe or show something fancy like an endless progress bar.
when the upload operation is completed of faulted, remove iframe and let the user know how it went.
When I moved to the FileReader API... was a good day.
While casually debugging some javascript on a web page, I noticed that Firefox (33.0 - Windows 7) Javascript console would not tell me if some .js files failed to load, so I decided to give this a closer look.
What I found is that if I have an HTML with a script tag pointing to a wrong local url, as the page loads the console shows no errors at all. Instead it shows the full path and file name for the wrong .js script as if there was nothing wrong with it.
I also tried with a button element issuing a xmlhttprequest to a non existing remote url, and same thing, no errors at all in the console when clicking.
$("#button").click(function(){
console.log("clicked me")
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
while "clicked me" will show as expected.
Also I verified that every possible log setting in developer tools is checked.
After reading that someone had luck with complete settings reset I went through that using Menu > Help > Troubleshooting > Reset Firefox settings. But... no. The errors still don't show up.
So, end of the story, given I just recently decided to look into this, and I can't exactly remember how long I've not been seeing errors exactly, I am questioning myself whether those kind of errors do not shown up at all in Firefox by design and if it's just a prerogative of Chrome... which, it goes by itself, shows all the errors (like for example "net::ERR_FILE_NOT_FOUND").
Anyone for a quick test on their console?
UPDATE, attaching screenshots of both Firefox and Chrome.
As you can see the situation is totally different.
Code:
Firefox Console Tab:
Also no errors on the missing files, whose name is just printed out normally in the console as if nothing was wrong with them.
Firefox Network Tab:
AS OPPOSED TO
Chrome Console Tab:
Chrome Network Tab:
After looking at the screenshots you added, I noticed that you were references resources on your local file system, so I decided to do some tests. I found that Firefox indeed does not report network errors for files on the local filesystem, reporting nothing on the console or the network tab, however it does report them properly for network resources. Unfortunately I could not reproduce the errors in chrome exactly, as my local filesystem is locked down rather tightly (I'm on an enterprise-owned system) and chrome simply reports that it doesn't have permission to access the local filesystem, regardless of whether the file exists or not (Firefox says nothing). Meanwhile, I imagine if you pointed your script/link tags to a network address such as a CDN, or if you are testing on a local test server something like:
http://localhost/[script-address]
it should report the error in both consoles.
Here's my test code:
And the firefox net panel
And the chrome console
Preserving my original answer below this point, as the JQuery API notes may be helpful for others who find themselves here
As mentioned in Ian's comment, and the JQuery API document at http://api.jquery.com/jQuery.getJSON/ JQuery's getJSON method will simply fail silently if you have a syntax error, the URL doesn't exist, or if it doesn't return a response. You can force it to do so by adding a .fail() method call to the end like so:
$("#button").click(function(){
console.log("clicked me")
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
}).fail(function() {
console.log("AJAX request failed");
});
});
You can also bind a function to the error event by using the .ajaxError method documented here: http://api.jquery.com/ajaxError/
$.ajaxError(function() {
console.log("AJAX request failed.");
});
Note that when you do it this way, JQuery will pass the function several useful parameters if you create variables to hold them, including the error event itself, the ajax object that triggered it, the settings that were used, and the error string, which you can then use to output whatever information you need to the console in order to debug what was causing your error. Good luck!