6 September 2024

This code snippet adds a custom "Edit" button to the CKEditor context menu, specifically for a widget with the class "my-widget." It first creates a new menu group called myWidgetGroup and then registers a menu item labeled "Edit My Widget," which is associated with the myWidgetEdit command and includes an optional icon. The context menu listener ensures that this option only appears when right-clicking a div element with the my-widget class. When the "Edit My Widget" option is clicked, the myWidgetEdit command is executed, triggering the edit functionality for the selected widget. The key is to have the correct command, so the widget dialog is correctly opened for the pre-existing widget.

Source code viewer
  1. if (editor.contextMenu) {
  2. editor.addMenuGroup('myWidgetGroup');
  3. editor.addMenuItem('myWidgetEdit', {
  4. label: 'Edit My Widget',
  5. // Provide an icon if needed.
  6. icon: this.path + 'icons/edit.png',
  7. command: 'myWidgetEdit',
  8. group: 'myWidgetGroup'
  9. });
  10.  
  11. editor.contextMenu.addListener(function(element) {
  12. if (element.getAscendant('div', true) && element.hasClass('my-widget')) {
  13. return { myWidgetEdit: CKEDITOR.TRISTATE_OFF };
  14. }
  15. });
  16.  
  17. editor.addCommand('myWidgetEdit', {
  18. exec: function(editor) {
  19. var widget = editor.widgets.focused;
  20. if (widget && widget.name === 'myWidget') {
  21. widget.edit();
  22. }
  23. }
  24. });
  25. }
  26. }
  27. });
Programming Language: Javascript