Search code examples
javascriptiosswiftwkwebviewuipasteboard

Cannot copy text from WKWebview to clipboard


I have WKWebview which opens up a google doc in text format. I was trying to copy the text in the view to have as a string in my code

I have used a custom UIMenJAuItem "Parse", when selected, selects the whole text and copy it to clipboard. But the problem is the clipboard is not able to load the text the first time.

I also tried evaluateJava scripts on the screen which didnt work due to Apples content secutity.

is there Anyway, i can achieve the result?

Following are my tries which were unsuccessful.

//Thorugh web view

extension ViewController:WKNavigationDelegate{
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.body.innerText") { (doc, error) in
            if doc != nil
            {print(doc!)}
            if let e = error
                {print(e.localizedDescription)}
        }
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void){
        return decisionHandler(.allow)
    }

}

By UIMenuItem

  override func viewDidLoad() {
        let menuItem = UIMenuItem(title: "Parse", action: #selector(ViewController.parse(_:)))

        UIMenuController.shared.menuItems = [menuItem]
}


@objc func parse(_ sender:UIMenuItem){
        webView.selectAll(sender)
        self.webView.copy(UIApplication.shared)
        print(UIPasteboard.general.string!)
    }

Solution

  • I have solved the issue.

    To have the text copied to clipboard you need to unload the webpage from view. ie, just apply select all, copy. Then if you load a new web page to the webview, you can have the copied text in UIPasteBoard.general.string