Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

wysiwyg

quill

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...

enter image description here

like image 929
HarlemSquirrel Avatar asked Dec 04 '16 06:12

HarlemSquirrel


2 Answers

The above solution won't 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 < this.PROTOCOL_WHITELIST.length; i++)
        if(value.startsWith(this.PROTOCOL_WHITELIST[i]))
          return value;

        return `http://${value}`
    }
    return value;
  }
}
Quill.register(CustomLink);
like image 133
Christopher Nsimbe Avatar answered Oct 27 '22 15:10

Christopher Nsimbe


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);
like image 43
Ben Browitt Avatar answered Oct 27 '22 15:10

Ben Browitt