6

When you long press a word on a WKWebView webpage, you will select it, and system will popup a menu to let you share/copy/lookup it so on. This is the iOS default behavior.

So my question is, how do you programmatically get a word from indicated point (CGPoint) on the WKWebView webpage?

Or, how do you programmatically select a word on WKWebView webpage without long press?

Any advice appreciated!

Jonny
  • 1,969
  • 18
  • 25

1 Answers1

1

First you must convert the point to the scrollview's coordinate system using convertPoint:toView:. You can use this point in a Javascript (with jQuery) function which will search the DOM node at this point:

function(inX, inY) {
    var theWindow = $(window);
    var theElement = document.elementFromPoint(
        inX - theWindow.scrollLeft(), inY - theWindow.scrollTop());

    return theElement == null ? null : theElement.textContent;
}
clemens
  • 16,716
  • 11
  • 50
  • 65
  • Not works for me. error from webView.evaluateJavaScript says $ is undefined. After I replace $(window) with window, it says scrollLeft is undefined. – Jonny Dec 04 '16 at 03:38
  • So I edit the script to this: `var theElement = document.elementFromPoint(\(point.x), \(point.y)); theElement == null ? null : theElement.textContent;` Now it can gives some content for me on the `point`, but instead give me a word, it gives me a whole sentence, which is not what I expected. – Jonny Dec 04 '16 at 03:47
  • You must include jQuery to get the $-expressions work. – clemens Dec 04 '16 at 09:24
  • hey, sorry, can you tell me how to add jquery in wkwebview? i can't make it. – Carl Hung Jul 04 '20 at 16:27
  • You can load jQuery into a string and execute it with https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript – clemens Jul 04 '20 at 17:09