Disable WKWebView zoom when clicking on text input HTML fields by injecting CSS

Rick_HK
2 min readMar 27, 2020

--

Unexpected zooming

When using WKWebView, user might need to go through some web forms pages. But it is such a pain in the ass if the page keeps zooming in when user clicks the input fields. The UX isn’t great as well because the user needs to be zoom out every time they finish filling in the forms.

There should be a few ways to prevent this user experience. Here is one of them:

1. Fix the font size of input fields when they are focused

For some reasons font-size 16px is the default value in WKWebView.

2. Make every input text fields in fixed font-size in CSS

The CSS should be something like this:

input, select:focus, textarea {

font-size: 16px !important;

}

3. Put the CSS via Javascript

The Javascript should be:

var style = document.createElement(‘style’); style.innerHTML = “input,select:focus, textarea {font-size: 16px !important;}”;

document.head.appendChild(style);

4. Use Javascript execution within the WKWebView

let javascriptFunction = `var style = document.createElement(‘style’); style.innerHTML = “input,select:focus, textarea {font-size: 16px !important;}”; document.head.appendChild(style);`

DispatchQueue.main.async(execute: {

self.webView.evaluateJavaScript(javascriptFunction) { (result, error) in

guard error == nil else {

return

}

}

})

5. Done ;)

It does not zoom!

Thats it. 🙂

Happy coding.

Find me at Twitter @rick3817

Reference:

--

--

Rick_HK
Rick_HK

Written by Rick_HK

Hi this is Rick from Hong Kong. I am a native iOS and Android mobile developer and also a tech enthusiast. Find me on Twitter https://twitter.com/rick3817

No responses yet