I have a mobile app written in SwiftUI. The user should be able to select (highlight) text in a WebView
, i.e. the blue handles should be shown:
But I don't want to show the context menu. Is this possible?
The "solutions" I have seen so far all disable text highlighting (e.g. How to disable user selection in a WKWebView in Swift?).
For reference, my WebView is a UIViewRepresentable
that creates a WkWebView
.
I have tried injecting Javascript:
let javascriptStyle = "var css = '*{-webkit-touch-callout:none;-webkit-user-select:none}'; var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; style.appendChild(document.createTextNode(css)); head.appendChild(style);"
webView.evaluateJavaScript(javascriptStyle, completionHandler: nil)
And sending nil
to the completion handler:
func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo, completionHandler: @escaping (UIContextMenuConfiguration?) -> Void) {
completionHandler(nil)
}
The first method will disable the selection completely, and the second method does not seem to have an effect.