• I am trying to insert text into Gutenberg at the current position for a speech to text solution.

    I am aware how to insert new blocks.

    
    const newBlock = wp.blocks.createBlock( "core/paragraph", {
        content: 'This is the content',
    });
    wp.data.dispatch( "core/editor" ).insertBlocks( newBlock );
    

    But I can’t figure out how to add a string at the current cursor position. Could somebody please give me a hint. Any help appreciated.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Hi @rockiger – You can try to use JavaScript to get the text(converted from speech) via API and insert that at the current cursor position.

    Thread Starter rockiger

    (@rockiger)

    Thanks @hiyottaunits,

    but what I don’t understand or don’t find, is an API, that lets me insert text at the current position in Gutenberg.

    Hi @rockiger – You can take a look at https://github.com/WordPress/gutenberg/tree/trunk/packages/editor

    Some packages are not fully documented. You might dig into source codes to find what you want.

    If you can work it out I’d be very interested as I basically have a plugin that under classic editor inserts text at the current cursor position.

    I don’t want my code to insert a new block, I need it to insert text into the current text block at the current cursor position.

    Surely there is a simple call for this?

    Thread Starter rockiger

    (@rockiger)

    If there is a simple call provided by Gutenberg, I can’t find it.

    Right now, my best bet is using the current window selection to insert text at the current cursor position:

    function insertTextAtCaret(text) {
        var sel, range;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
                range.insertNode( document.createTextNode(text) );
            }
        } else if (document.selection && document.selection.createRange) {
            document.selection.createRange().text = text;
        }
    }

    At the end Gutenberg uses contentEditable.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Insert text at the current cursor position with JavaScript’ is closed to new replies.