link.js 1.1 KB

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