1

Having done next to none JavaScript before, I've tried several ways to position the caret (to end) in a JavaFX HTMLEditor without success.

For example, I've tried this: contenteditable, set caret at the end of the text (cross-browser) by adding the function placeCaretAtEnd(el) in the <script>-section, something like this (I omitted the <script> section here):

<html>
<head>
<style>
</style>
</head>
<body onLoad='document.body.focus();' onfocus='placeCaretAtEnd(document.body);' contenteditable='true'>
</body>
</html>

(I set this via HTMLEditor.setHtmlText)

But the caret stays at the beginning.. has anyone successfully positioned the caret in a JavaFX HTMLEditor?

Community
  • 1
  • 1
user2499946
  • 679
  • 1
  • 10
  • 28

1 Answers1

0

Well I got it working finally. I'm not sure why the onfocus didn't work..

public void requestFocus() {
        HTMLEditorSkin skin = (HTMLEditorSkin) editor.getSkin();
        try {
            Field f = skin.getClass().getDeclaredField("webView");
            f.setAccessible(true);
            WebView wv = (WebView) f.get(skin);
            Platform.runLater(() -> {
                wv.requestFocus();
                wv.getEngine().executeScript("document.body.focus()");
                wv.getEngine().executeScript(
                                "var el = document.body;\n" +
                                "if (typeof window.getSelection != \"undefined\"\n" +
                                "            && typeof document.createRange != \"undefined\") {\n" +
                                "        var range = document.createRange();\n" +
                                "        range.selectNodeContents(el);\n" +
                                "        range.collapse(false);\n" +
                                "        var sel = window.getSelection();\n" +
                                "        sel.removeAllRanges();\n" +
                                "        sel.addRange(range);\n" +
                                "    } else if (typeof document.body.createTextRange != \"undefined\") {\n" +
                                "        var textRange = document.body.createTextRange();\n" +
                                "        textRange.moveToElementText(el);\n" +
                                "        textRange.collapse(false);\n" +
                                "        textRange.select();\n" +
                                "    }");
            });
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
user2499946
  • 679
  • 1
  • 10
  • 28