suneditor

How to insert custom HTML at the cursor's position in Suneditor


There is a WYSIWYG editor called "suneditor". I want to install a custom button on it and insert the HTML "<p>welcome!</p>" at the cursor's position when the button is pressed. I have tried various methods, but I have not been able to do it successfully. How should I configure it?

I was able to add a div and a class using the following code.

var plugin_command = {
            name: 'customCommand',
            display: 'command',
            title: 'test',
            buttonClass: '',
            innerHTML: '<i class="fas fa-carrot"></i>',

            add: function(core, targetElement) {
                const context = core.context;
                const rangeTag = core.util.createElement('div');
                core.util.addClass(rangeTag, '__se__format__range_custom');
                context.customCommand = {
                    targetButton: targetElement,
                    tag: rangeTag
                };
            },

            active: function(element) {
                if (!element) {
                    this.util.removeClass(this.context.customCommand.targetButton, 'active');
                } else if (this.util.hasClass(element, '__se__format__range_custom')) {
                    this.util.addClass(this.context.customCommand.targetButton, 'active');
                    return true;
                }

                return false;
            },

            
            action: function() {
                const rangeTag = this.util.getRangeFormatElement(this.getSelectionNode());
                if (this.util.hasClass(rangeTag, '__se__format__range_custom')) {
                    this.detachRangeFormatElement(rangeTag, null, null, false, false);
                } else {
                    this.applyRangeFormatElement(this.context.customCommand.tag.cloneNode(false));
                }
            }

            
        }

Thank you in advance.


Solution

  • Use "insertNode" to insert, and "nodeChange" to change the style of the selected text.

    const tag = this.util.createElement("p");
    tag.textContent = "abcde";
    // insert at the current cursor position
    this.insertNode(tag, null, true);
    
    this.history.push(false);

    refer: https://github.com/JiHong88/suneditor/blob/master/src/plugins/dialog/link.js#L120 http://suneditor.com/sample/html/out/document-editor.html#insertNode http://suneditor.com/sample/html/out/document-editor.html#nodeChange