validate.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { isStr } from "./utils";
  2. export const validateContent = (svgContent) => {
  3. const div = document.createElement('div');
  4. div.innerHTML = svgContent;
  5. // setup this way to ensure it works on our buddy IE
  6. for (let i = div.childNodes.length - 1; i >= 0; i--) {
  7. if (div.childNodes[i].nodeName.toLowerCase() !== 'svg') {
  8. div.removeChild(div.childNodes[i]);
  9. }
  10. }
  11. // must only have 1 root element
  12. const svgElm = div.firstElementChild;
  13. if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') {
  14. const svgClass = svgElm.getAttribute('class') || '';
  15. svgElm.setAttribute('class', (svgClass + ' s-ion-icon').trim());
  16. // root element must be an svg
  17. // lets double check we've got valid elements
  18. // do not allow scripts
  19. if (isValid(svgElm)) {
  20. return div.innerHTML;
  21. }
  22. }
  23. return '';
  24. };
  25. export const isValid = (elm) => {
  26. if (elm.nodeType === 1) {
  27. if (elm.nodeName.toLowerCase() === 'script') {
  28. return false;
  29. }
  30. for (let i = 0; i < elm.attributes.length; i++) {
  31. const name = elm.attributes[i].name;
  32. if (isStr(name) && name.toLowerCase().indexOf('on') === 0) {
  33. return false;
  34. }
  35. }
  36. for (let i = 0; i < elm.childNodes.length; i++) {
  37. if (!isValid(elm.childNodes[i])) {
  38. return false;
  39. }
  40. }
  41. }
  42. return true;
  43. };
  44. export const isSvgDataUrl = (url) => url.startsWith('data:image/svg+xml');
  45. export const isEncodedDataUrl = (url) => url.indexOf(';utf8,') !== -1;