2

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: Highlighting

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.

km11
  • 528
  • 3
  • 12
  • Supposedly you can implement the `WKUIDelegate` method `webView(_:contextMenuConfigurationForElement:completionHandler:)` and call the completion handler with `nil` but it only seems to be called for links, not other text. – HangarRash Jun 20 '23 at 00:17
  • Thanks for the suggestion, but as you said it did not work. – km11 Jun 20 '23 at 08:22

1 Answers1

2

try to use this for selection

For reference you can see this link also

How do I get the selected text from a WKWebView from objective-C

webView.configuration.userContentController.add(self, name: "newSelectionDetected")

let scriptString = """
function getSelectionAndSendMessage()
{
    var txt = document.getSelection().toString() ;
    window.webkit.messageHandlers.newSelectionDetected.postMessage(txt);
}
document.onmouseup = getSelectionAndSendMessage;
document.onkeyup = getSelectionAndSendMessage;
document.oncontextmenu = getSelectionAndSendMessage;"""

let script = WKUserScript(source: scriptString, injectionTime: .atDocumentEnd, forMainFrameOnly: true)

webView.configuration.userContentController.addUserScript(script)

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
// Use message.body here

}

Chandaboy
  • 1,302
  • 5
  • 10