Getting Selected Text UIWebView

I am trying to access the current selected text in a UIWebView using the following line of code:

 NSString *highlighted = [_webView stringByEvaluatingJavaScriptFromString:@"window.getSelection();"]; 

But it only returns the emtpy string. Any ideas on what I am missing?

+4
source share
5 answers

Try the following:

 NSString * highlighted = [_webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"]; 
+4
source

I also stumbled upon this problem and it really is frustrating. I don’t remember exactly where I got the solution from, but this is the following; getSelection() returns a JavaScript object that cannot be converted to a string. You must explicitly convert it to a string from JavaScrtipt code:

 NSString *highlighted = [_webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString();"]; 

Look in action.

+1
source

I think this will help

 NSString *selection = [self.webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"]; 

Also check the link

+1
source

In swift: self.webView.stringByEvaluatingJavaScriptFromString ("window.getSelection (). ToString ();")

A semicolon at the end of Javascript is required; without it, this did not work!

+1
source

Try it fast:

 // stringByEvaluatingJavaScript retunr optional string, hence use if-let block if let selectedString = self.webView.stringByEvaluatingJavaScript(from: "window.getSelection().toString()") { print(selectedString - \(selectedString)) } 
0
source

Source: https://habr.com/ru/post/1435640/


All Articles