Mike
@mikerfulcher on Twitter
6twenty on GitHub
Want to test if a browser supports base64 encoding? It's surprisingly easy :)
- // create a new image...
- var image = document.createElement('img');
- // define an onload callback...
- image.onload = function() {
- testImage(image);
- }
- // set the source to a small base64 encoded image which has known dimensions
- // in this case, a 1x1 pixel gif...
- image.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
- // test whether the loaded image has the correct dimensions (1x1 pixel)
- // browsers which don't support base64 won't be able to render the image, so
- // image.width and image.height won't return the expected values
- function testImage(image) {
- var body = document.getElementsByTagName('html')[0];
- if (image.width == 1 && image.height == 1) {
- body.className = body.className + ' base64';
- } else {
- body.className = body.className + ' noBase64';
- }
- }
- // our <html> now has an additional class which we can reference...
- console.log(document.getElementsByTagName('html')[0]);
- // => <html class=" base64"> ... </html>
Posted Nov 16th, 2011. Tagged javascript, base64
blog comments powered by Disqus
© 2011 rawnet.com