tinymce / tinymce-blazor

Blazor integration
MIT License
45 stars 13 forks source link

Custom Button with C# Function Call #32

Closed curea closed 2 years ago

curea commented 2 years ago

I am trying to replicate the following code in TinyMCE.Blazor:

editor.addButton('mybutton', { text: "My Button", onclick: function () { alert("My Button clicked!"); } });

Is there a simple way to add a custom button and call a function?

exalate-issue-sync[bot] commented 2 years ago

Ref: INT-2731

jscasca commented 2 years ago

@curea currently the only way to add buttons is by creating a js configuration object and adding those buttons in the setup function. To call a Blazor function you will need to call the DotNet.invokeMethodAsync("<your_blazor_fn>", args..);

curea commented 2 years ago

Is there an example of creating one in a js configuration object somewhere? I've really been struggling with this, so any help would be really appreciated.

jscasca commented 2 years ago

@curea I made a quick sample you can find in https://github.com/jscasca/SampleTinyMceBlazor

You can create a config in your js files and load that configuration as long as it is part of the window object. For example in the index.html:

 <script>
        const invokeCustomFn = (val) => {
            DotNet.invokeMethodAsync("SampleTinyMceBlazor", "CustomFn", val);
        };
        window.my = {
            tinyConf: {
                setup: (e) => {
                    e.ui.registry.addButton('customBn', {
                        onAction: () => {
                            invokeCustomFn(e.getContent());
                        },
                        text: 'sample'
                    });
                }
            }
        }
    </script>

You can specify the js config by using the JsConfSrc. For example:

<Editor id="Sample1" JsConfSrc="my.tinyConf" Conf="@basicConf"></Editor>

@code {

  private Dictionary<string, object> basicConf = new Dictionary<string, object>();

  protected override Task OnInitializedAsync()
  {
    basicConf.Add("height", 300);
    basicConf.Add("menubar", false);
    basicConf.Add("toolbar", "undo redo | bold italic | customBn");
    return base.OnInitializedAsync();
  }

  [JSInvokable("CustomFn")]
  public static void DebugString(string val)
  {
    Console.WriteLine($"debugging val [{val}]");
  }
}
curea commented 2 years ago

Thank you, this is very helpful and works great!