I am building an app using Capacitor to embed my website as the main portion of the app where there are portions that I want to be able to pinch-zoom (a photo gallery, for example). I've found answers about the Android WebViews and the HTML meta
tag using the maximum-scale
setting, like so, but after changing the meta tag the webview still doesn't support pinch zooming. Is there a way to override the Capacitor settings to allow zooming?
I found the answer after getting some clues from a GitHub issue where they modified the Capacitor BridgeActivity
class code to change the WebView initialization, but I didn't really want to modify code that might be automatically generated or is part of the capacitor core, so I found a way to do it with plugins.
Writing the following ZoomPlugin
class allows me to access the WebView through the bridge
attribute and modify the zoom setting:
package com.example.app;
import com.getcapacitor.Plugin;
import com.getcapacitor.annotation.CapacitorPlugin;
@CapacitorPlugin(name = "Zoom")
public class ZoomPlugin extends Plugin {
@Override
public void load() {
this.bridge.getWebView().getSettings().setBuiltInZoomControls(true);
// disables zoom in/zoom out buttons in the webview, to only allow pinch to zoom
this.bridge.getWebView().getSettings().setDisplayZoomControls(false);
}
}
After writing the plugin, register it in the MainActivity
class:
package com.example.app;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(ZoomPlugin.class);
}
}
Now pinch-to-zoom should work as long as your meta
tag is set correctly, as mentioned in other answers:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2.5" />
The important part of this being maximum-scale=2.5
which will set the zoom limit to be 2.5x. You can disable zoom for a page by setting maximum-scale
to be the same as initial-scale
.