Search code examples
javascriptgoogle-chromewebkitcompression

Native javascript decompress function in Chrome/webkit


If you are sending data that is base64-encoded and compressed (using, say, python's zlib.compress()), you can use the native Chrome function window.atob() to convert from base64 to binary data. Is there any similar native javascript function to decompress the zlib-compressed data? Is there some hack to do this?

I know that code to decompress data is already in the browser because it can receive HTML sent with gzip headers.

I am not looking for a javascript library to do decompression.

If you come up a decompression scheme on the browser, I can compress it in that format for transmission. In other words, any decompression routine is acceptable.


Solution

  • 2020 Update

    Chrome 80+ supports CompressionStream and DecompressionStream APIs

    Gzip-compress a stream

    const compressedReadableStream = inputReadableStream.pipeThrough(new CompressionStream('gzip'));
    

    Deflate-compress an ArrayBuffer

    function compressArrayBuffer(input) {
      const stream = new Response(input).body
        .pipeThrough(new CompressionStream('deflate'));
      return new Response(stream).arrayBuffer();
    }
    

    Gzip-decompress a Blob to a Blob

    This treats the input as a gzip file regardless of the mime-type. The output Blob has an empty mime-type.

    async function DecompressBlob(blob) {
      const ds = new DecompressionStream('gzip');
      const decompressedStream = blob.stream().pipeThrough(ds);
      return await new Response(decompressedStream).blob();
    }
    

    https://github.com/WICG/compression/blob/master/explainer.md