Nowadays, most modern browsers support the WebP image format. In some cases, it may be necessary to check if the user's browser supports WebP images.
Here, we will demonstrate a simple method to detect WebP support on the client side using JavaScript.
<script> function isWebpSupported(callback) { var webpData = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA='; fetch(webpData) .then(response => response.blob()) .then(blob => callback(blob.type === 'image/webp')) .catch(() => callback(false)); } function handleWebpSupport(isSupported) { if (isSupported) { console.log('WebP format is supported!'); } else { console.log('WebP format is not supported.'); } } isWebpSupported(handleWebpSupport); </script>
Let's examine the JavaScript code.
In the isWebpSupported() function, a small WebP image encoded in Base64 is set as the variable webpData. The function then tries to fetch this image. It will respond with a blob.type, and we will check if it is a WebP image type. It also handles other scenarios and makes a callback with a false parameter.
The second function, handleWebpSupport(), works as a callback to print out the result.
Using this simple JavaScript code, we can determine whether the browser supports the WebP image format or not.