With WKWebView's, the keyboard functionality is limited much more than on a textfield but you do have options depending on what you are wanting to modify.
Preventing keyboards and text interaction:
You can update the configuration so that text inputs and text highlighting is disabled using:
webView.configuration.preferences.isTextInteractionEnabled =
false
You can also prevent the keyboard from displaying entirely by adding an observer that will dismiss the keyboard whenever it is about to open using:
NotificationCenter.default.addObserver(
forName: UIResponder.keyboardWillShowNotification,
object: nil,
queue: OperationQueue.main
) { [weak self] _ in
Task { @MainActor [weak self] in
self?.webView.endEditing(true)
}
}
Prevent specific input characters:
document.body.addEventListener('keydown', function(e) {
if (e.key === " " || e.keyCode === 32) {
e.preventDefault();
return;
}
});
Modifying the keyboard type(ish):
If you are wanting to modify the keyboard type, @Justin Michael already covered the solution of modifying the textfields inputmode
using javascript injected into the webView. Unfortunately, as of now there doesn't seem to be a more effective way to modify the keyboard type in a webView like there is for a textfield.
I tried method swizzling the UIKeyboardType
after seeing this solution https://stackoverflow.com/a/47949089/29871479 but I couldn't get it to properly update the keyboard type still. It seemed like the underlying WKContentView
would fail to get overridden. This could be due to WebKits internal handling of the keyboard in its view hierarchy? It might be possible to do but I haven't found any resources online providing a solution for it and I wasn't able to achieve it
To have full control over a WKWebView's keyboard, creating a custom keyboard is probably the best solution but its more inconvenient. However, if you just need to modify specific behaviors or settings, I hope the solutions I suggested above help!