When adding links with the Quill editor I must include the protocol or the link is treated as a relative link.
When someone adds a link without specifying any protocol I would like to append https:// by default so when a user types google.com it will create a link to https://google.com instead of https://example.com/google.com
This solution worked for me:
import Quill from 'quill';
const Link = Quill.import('formats/link');
// Override the existing property on the Quill global object and add custom protocols
Link.PROTOCOL_WHITELIST = ['http', 'https', 'mailto', 'tel', 'radar', 'rdar', 'smb', 'sms'];
class CustomLinkSanitizer extends Link {
static sanitize(url: string) {
// Run default sanitize method from Quill
const sanitizedUrl = super.sanitize(url);
// Not whitelisted URL based on protocol so, let's return `blank`
if (!sanitizedUrl || sanitizedUrl === 'about:blank') return sanitizedUrl;
// Verify if the URL already have a whitelisted protocol
const hasWhitelistedProtocol = this.PROTOCOL_WHITELIST.some(function(protocol: string) {
return sanitizedUrl.startsWith(protocol);
});
if (hasWhitelistedProtocol) return sanitizedUrl;
// if not, then append only 'https' to not to be a relative URL
return `https://${sanitizedUrl}`;
}
}
Quill.register(CustomLinkSanitizer, true);