How can I prefill links with http in a Quill editor?

孤者浪人 提交于 2020-07-05 12:34:19

问题


When adding links with the Quill editor I must include the protocol or the link is treated as a relative link.

When someone clicks to add a link I would like to have the field prepopulate with http:// so when a user types google.com it will create a link to http://google.com instead of http://myapp.net/something/google.com.

Stack overflow does this...


回答1:


The above solution wont work when you try to save an existing link. Also it ignores other protocols such as ( mailto, tel, https )

Here is a better solution:

let Link = window.Quill.import('formats/link');

class CustomLink extends Link {

  static sanitize(url) {
    let value = super.sanitize(url);
    if(value)
    {
      for(let i=0;i<CustomLink.PROTOCOL_WHITELIST.length;i++)
        if(value.startsWith(CustomLink.PROTOCOL_WHITELIST[i]))
          return value;
      return `http://${value}`
    }
    return value;
  }
}
Quill.register(CustomLink);



回答2:


You can extend the link format with custom logic:

var Link = Quill.import('formats/link');

class MyLink extends Link {
  static create(value) {
    let node = super.create(value);
    value = this.sanitize(value);
    if(!value.startsWith("http")) {
      value = "http://" + value;
    }
    node.setAttribute('href', value);
    return node;
  }
}

Quill.register(MyLink);


来源:https://stackoverflow.com/questions/40956020/how-can-i-prefill-links-with-http-in-a-quill-editor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!