link.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import Inline from '../blots/inline';
  2. class Link extends Inline {
  3. static create(value) {
  4. let node = super.create(value);
  5. value = this.sanitize(value);
  6. node.setAttribute('href', value);
  7. node.setAttribute('rel', 'noopener noreferrer');
  8. node.setAttribute('target', '_blank');
  9. return node;
  10. }
  11. static formats(domNode) {
  12. return domNode.getAttribute('href');
  13. }
  14. static sanitize(url) {
  15. return sanitize(url, this.PROTOCOL_WHITELIST) ? url : this.SANITIZED_URL;
  16. }
  17. format(name, value) {
  18. if (name !== this.statics.blotName || !value) return super.format(name, value);
  19. value = this.constructor.sanitize(value);
  20. this.domNode.setAttribute('href', value);
  21. }
  22. }
  23. Link.blotName = 'link';
  24. Link.tagName = 'A';
  25. Link.SANITIZED_URL = 'about:blank';
  26. Link.PROTOCOL_WHITELIST = ['http', 'https', 'mailto', 'tel'];
  27. function sanitize(url, protocols) {
  28. let anchor = document.createElement('a');
  29. anchor.href = url;
  30. let protocol = anchor.href.slice(0, anchor.href.indexOf(':'));
  31. return protocols.indexOf(protocol) > -1;
  32. }
  33. export { Link as default, sanitize };