使用Swift 4

时间:2018-04-27 02:13:16

标签: javascript ios swift webkit

我正在使用WKWebKit,并且希望能够通过一次快速点击将HTML文档中的单词复制到单独的视图。

我正在采用的方法是添加一个TapGestureRecognizer,然后使用JavaScript的document.caretRangeFromPoint()来查找实际文本。但事实并非如此,我不确定为什么不这样做。

相关代码如下。我完整地留下了一些额外的调试代码,用于打印document.elementFromPoint()的值。它始终按预期运行,返回页面上的相应元素只是为了让我知道正确设置了视图和位置。

感谢您提供的任何帮助。

代码:

@objc public func HandleTapFrom (recognizer : UITapGestureRecognizer)
{    
    let myView = recognizer.view as? WKWebView
    let location: CGPoint = recognizer.location(in: myView)

    // .caretRangeFromPoint which never returns anything
    var js = String("document.caretRangeFromPoint(\(location.x),\(location.y)).toString()")
    myView?.evaluateJavaScript(js) { (result, error) in
        print("-------------")
        if error != nil {
            print("\ncaretRangeFromPoint Error:", error as Any)
        } else {
            print("\ncaretRangeFromPoint Success:",result as Any)
        }
    }

    // elementFromPoint, which works as expected.
    js = String("document.elementFromPoint(\(location.x),\(location.y)).toString()")
    myView?.evaluateJavaScript(js) { (result, error) in
        if error != nil {
            print("\nelementFromPoint Error:", error as Any)
        } else {
            print("\nelementFromPoint Success:",result as Any)
        }
    }
}

调试输出:

caretRangeFromPoint Success: Optional()
elementFromPoint Success: Optional([object HTMLSpanElement])
-------------
caretRangeFromPoint Success: Optional()
elementFromPoint Success: Optional([object HTMLElement])
-------------
caretRangeFromPoint Success: Optional()
elementFromPoint Success: Optional(https://developer.mozilla.org/en-US/docs/MDN/Contribute/Guidelines/Conventions_definitions#Experimental)
-------------
caretRangeFromPoint Success: Optional()
elementFromPoint Success: Optional([object HTMLParagraphElement])

0 个答案:

没有答案