Detecting base64 support in javascript

Mike
@mikerfulcher on Twitter
6twenty on GitHub

Want to test if a browser supports base64 encoding? It's surprisingly easy :)

  1. // create a new image...
  2. var image = document.createElement('img');
  3. // define an onload callback...
  4. image.onload = function() {
  5. testImage(image);
  6. }
  7. // set the source to a small base64 encoded image which has known dimensions
  8. // in this case, a 1x1 pixel gif...
  9. image.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
  10. // test whether the loaded image has the correct dimensions (1x1 pixel)
  11. // browsers which don't support base64 won't be able to render the image, so
  12. // image.width and image.height won't return the expected values
  13. function testImage(image) {
  14. var body = document.getElementsByTagName('html')[0];
  15. if (image.width == 1 && image.height == 1) {
  16. body.className = body.className + ' base64';
  17. } else {
  18. body.className = body.className + ' noBase64';
  19. }
  20. }
  21. // our <html> now has an additional class which we can reference...
  22. console.log(document.getElementsByTagName('html')[0]);
  23. // => <html class=" base64"> ... </html>​

Posted Nov 16th, 2011. Tagged javascript, base64


blog comments powered by Disqus



© 2011 rawnet.com