1

What method is available to select text on webkit2gtk. I could not find anything on the API for Vala webkit2.

The requirement is to get the selected text on a webpage after the user releases the mouse after text selection.

Priyantha
  • 4,839
  • 6
  • 26
  • 46
Siddhartha Das
  • 251
  • 1
  • 8

1 Answers1

2

The only API for getting the current selection is via the DOM selection API. It is a bit awkward to get access to the DOM in WebKitGTK+ since the DOM representation exists in the memory of the web process, which is separate from the application process that has the WebKit.WebView widget.

To bridge between the two, you can call WebKit.WebView.run_javascript() and pass the appropriate JavaScript code through to be executed in the web process, something like:

web_view.run_javascript("window.getSelection().getRangeAt(0).toString()")

To use this method, you will need to use vala 0.38, or import the JavaScriptCore VAPI into your own project (like Geary does), so you can work out what the return value is.

Note also that you'll probably want to add some checks to this: that there is at least one range in the DOM selection object, and so on.

Michael Gratton
  • 516
  • 2
  • 10
  • 1
    Many thanks, I had already started using WebKit.WebView.run_javascript() as a fallback and used the javascript function described here[https://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text] for getting selection text. Then used the value from that function to set the document title which can be fetched back with WebView.get_title() method. Pity that a more native gtk control is not readily available for DOM access. Accepting this as the answer. – Siddhartha Das Sep 28 '17 at 09:21
  • Ah yes, I had forgotten about the old set title/get title trick. It is certainly the easiest workaround for JavaScriptCore being missing from earlier vala releases. – Michael Gratton Sep 28 '17 at 13:13