Search code examples
javascriptcallbackhreftext-editorwysihtml5

Is there a way to let wysithtml5's link editor let the user add anything they like to the href tag?


I'm using the wysithtml5 editor, but users are reporting a lot of issues with adding links. User want to add whatever they want to the href attribute. However when clicking 'ok' on adding the link it runs through some sort of call back the modified it..

For example is the user want to add an anchor tag:

#moo

The link that will be entered is the documents url followed by the ancors so it would end up looking like this:

http://stackoverflow.com/#moo

The same happens if they try to add a liquid tag for example:

{{name}}

becomes…

http://stackoverflow.com/84748/%7B%7Bname%7D%7D

Is there anyway to modify wysithtml5 so it does not go through this callback that modified the href attribute? I've tried removing / modifing the checkAttributes from the parser rules however this has had no effect. There is something else processing the href too.

Thanks!


Solution

  • wysihtml5 is not explicitly doing this conversion. This is the result of the weird behavior of the DOM objects it is creating to represent the anchor tags. Basically, anchor.href and anchor.getAttribute('href') don't necessarily return the same thing.

    Here is an example you can execute on the Javascript console to see for yourself:

    var anchor = document.createElement('a');
    anchor.setAttribute('href', '#foo');
    console.log(anchor.href); //prints anchor.baseURI + '#foo'
    console.log(anchor.getAttribute('href')); //prints '#foo'
    

    Anyway, I would consider this a bug in wysihtml5. As far as I can tell, you only need to change two lines in the source to fix it. See my fork on Github: https://github.com/b3nj4m/wysihtml5/commit/c14d746b2b192b043673d97f79f3f61c23908f8d

    Edit: concerning the href attribute being stripped-out during the raw html -> composer view conversion, that is due to the parser rules. I think the best way to handle this is to add a new rule like not_empty, and use that for href.

    e.g.

    "a": {
      "check_attributes": {
        "href": "url"
      },
      //...
    }
    

    becomes

    "a": {
      "check_attributes": {
        "href": "not_empty"
      },
      //...
    }
    

    and then you add a not_empty rule in src/dom/parse.js

    var attributeCheckMethods = { 
      not_empty: function(attributeValue) {
        return attributeValue || null;
      },  
      //...
    };
    

    See the change to src/dom/parse.js here: https://github.com/b3nj4m/wysihtml5/commit/0ef0dad5f0457266057d7e14df42dafe987bdb69#L2R374