Search code examples
javaandroidwebviewandroid-webviewzooming

Zooming a WebView


I don't want to change the scale of the webView. That means, I know how to enable pinch to zoom and stuff like that, where only the visible part of the page is altered ("zoomed in"), as with

webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);

I also don't want to change the fontSize, as possible with getSettings().setTextZoom(zoom).

What I want to achieve is the same zoom as possible in browsers for the Computer, e.g. Firefox. Here you can zoom for example with CTRL + +. But it doesn't change the scale nor changes it only the font size. It zooms everything, while at the same time kind of rearranging the contents of the page to fit the new space available in the zoomed browser window. Is something like that possible with the android webView?


A few images to show what I want:

The default view:default

The scaled view:scaled

The font zoomed view:font zoomed

What I want:optimal


Solution

  • I found two possible solutions to this:

    1. JS Zoom

    This option loads a JS snippet into the current site of the webView and updates the style property of the current body. The Javascript snippet looks like that:

    function Zoom(value)
    {
        document.body.style.zoom = value;
    }
    

    I use the loadUrl method of the webView to load this snippet. The disadvantage of this method is that you have to load the snippet every time the page is updated. I did this by updating the zoom whenever onPageFinished of the webView is called. This has the disadvantage that the zoom isn't applied directly, but only when the page has finished loading.

    2. DPI change

    This is a rather hacky solution. It simulates a new display size, causing everything (and hence also the contents of the webView) to resize. It is done by executing the following command in the linux subsystem:

    wm density [value]
    

    Where the value is the new screen density. It has to be executed with root privileges, which also is the main disadvantage of this solution. Another disadvantage is that it is pretty slow (it needs about a second before updating the DPI).