Search code examples
javascripthtmlwysiwygwysihtml5

wysihtml5 - how disable underline tag


I have a small problem with wysihtml5 on my site. I want to allow only a few html tags and if I remove underline from parser rules and even underline command from wysihtml5 library, I can still press CTRL(command)+U to make selected text underlined. What should I do to get rid of this behaviour? Thanks for any advices.


Solution

  • New answer: Here is my updated solution. I updated the existing keydown event handler (and added a keyup handler for tracking ctrl pressed state) as follows:

    // --------- Shortcut logic ---------
    var ctrlDown = 0;
    
    dom.observe(element, "keydown", function(event) {
      var keyCode  = event ? event.which : window.event.keyCode,
        command    = shortcuts[keyCode];
      if (1 == event.ctrlKey) {
        console.log('Ctrl key pressed. Setting ctrlDown = 1.');
        ctrlDown = 1;
      }
      if (85 == keyCode && 1 == ctrlDown) {
        console.log('Pressed "U" (keyCode 85), but Ctrl key still down. Don\'t fire!');
        return event.preventDefault(), !1;
      }
      if (1 == ctrlDown && !event.altKey && command) {
        console.log('Shortcut Ctrl + keyCode ' + keyCode + ' triggered.');
        that.commands.exec(command), event.preventDefault();
      }
    });
    
    dom.observe(element, "keyup", function(event) {
      // note: "event.ctrlKey" doesn't work with keyup, use keyCode/which 
      if (17 == (event ? event.which : window.event.keyCode)) {
        console.log('Ctrl key released. Setting ctrlDown = 0.');
        ctrlDown = 0;
      }
    });
    

    I sent you a pull request at github.


    Original answer: All I needed to do, to disable the Ctrl+u keyboard shortcut, was to remove the keyCode for "u" (85) from the shortcuts object at line 8494 in wysihtml5-0.4.0pre.js.

    Change

      shortcuts = {
        "66": "bold",     // B
        "73": "italic",   // I
        "85": "underline" // U
      };
    

    to

      shortcuts = {
        "66": "bold",     // B
        "73": "italic"    // I
      };
    

    and you will no longer be able to use the Ctrl+u shortcut within the editor.

    Alternatively, you could catch the keydown events and disable the Ctrl+u shortcut (ie. prevent default behaviour). Something like:

    // --------- disable ctrl+u shortcut for underlining texts ---------
    dom.observe(element, "keydown", function(event) {
      if ((event.ctrlKey || event.metaKey) && 'u' == String.fromCharCode(event.which).toLowerCase()) {
        // do something
      }       
    });