Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent image load errors going to the javascript console

Tags:

For example in javascript

var image = new Image(); image.onerror = function(e) {     // handle error my way } image.src = "http://bad.location.com/img.jp" 

I've tried

e.preventDefault() return false 

but the error is still logged to the console. Maybe this is not such a bad thing but what I'm doing is uploading files to the server and then processing them and loading the artifacts to S3. This all takes a long time. I do this in the background and return the S3 URL's to the browser early and use some javascript to ping the image urls using the image.onerror callback to detect if the image is arrived on S3 or not.

It all works but I get a load of console errors. This is a bit ugly. Is there any way to hide this.

like image 367
bradgonesurfing Avatar asked Mar 27 '12 16:03

bradgonesurfing


2 Answers

Sorry there is seemingly no way to suppress that error, at least in Google Chrome.

See also: Check if file exists but prevent 404 error in console from showing up

like image 173
Simon Sarris Avatar answered Jan 04 '23 01:01

Simon Sarris


Thought to share what I just discovered. :) Googling around didn't help, so I've spent quite some time and seems like it worth it! There is indeed one solution (if you control the backend too)

For example in nodejs:

 /*  * Custom 404 middleware to handle missing image for certain routes  */  const path = require ( 'path' ); const fs = require ( 'fs-extra' );  // @root - root folder // @exclude - exclude folder module.exports = ( root, exclude ) => ( req, res, next ) => {      if ( req.originalUrl.match ( exclude ) ) {         fs.stat ( path.join ( root, req.originalUrl ), function ( err, stat ) {              if ( err === null ) {                  // if file exist call next = fallback to static handler                 next ();              } else {                  // if file does not exist, return a fake 200 img response                 res.writeHead ( 200, {                     'Content-Type'  : 'image/png',                     'Content-Length': 0,                     'Cache-Control' : 'public, max-age=0',                     'X-Status'      : '404'                 } );                  return res.end ();             }         } );     } else {         next ();     }  }; 

Then you can call it like:

let static_path = path.join ( __dirname, 'public' ); app.use ( require ( './middleware/missing-image' ) ( static_path, 'img/path' ) ); app.use ( express.static ( static_path ) ); 

X-Status is just a custom header added so you can detect in client side JS that the response been overwritten.

Note: res.end() can be used to stream back a fallback image too.

like image 36
ShQ Avatar answered Jan 04 '23 00:01

ShQ