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

后端 未结 3 2019
花落未央
花落未央 2020-12-06 07:49

I have a WKWebView.

When the user right-clicks on it, I can customize a contextual menu in my objective-c method. I\'d like to add a menu item only if the user has s

3条回答
  •  鱼传尺愫
    2020-12-06 07:58

    Swift 5 translation

    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
    }
    

提交回复
热议问题