Get word under tap from UIWebView using JavaScript

2020-07-22 03:18发布

问题:

I'm displaying some local web content and would like to get the word under the tap point. The single tap delegate is setup and I can get it to work great if I use a UITextView and load the HTML with a NSAttributedString and NSHTMLTextDocumentType, but I lose formatting such as paragraph spacing and small caps; adding a NSMutableParagraphStyle is without effect.

Using a UIWebView and loadHTMLString that includes JQuery, is there a way? There are several pages which show how to use JS to get the word under the cursor, such as the following:

How to get a word under cursor using JavaScript?

How to get word under cursor?

Get word under mouse pointer

Is it possible to get the word under the mouse cursor in a `<textarea>`? How to get word under cursor?

But after several days, I've been unable to get it to work. My code:

var jsFile = NSBundle.mainBundle().pathForResource("webview", ofType: "js");
let jsData = NSString(contentsOfFile:jsFile!, encoding:NSUTF8StringEncoding, error:nil) as! String
let returned = webView.stringByEvaluatingJavaScriptFromString(jsData)! as String
println("Returned \(returned).")

The word could be unicode with a different code range, but getting any word to work first would be wonderful.