(untrustedString: IonicSafeString | string | undefined)
| 5 | * in an untrusted string |
| 6 | */ |
| 7 | export const sanitizeDOMString = (untrustedString: IonicSafeString | string | undefined): string | undefined => { |
| 8 | try { |
| 9 | if (untrustedString instanceof IonicSafeString) { |
| 10 | return untrustedString.value; |
| 11 | } |
| 12 | if (!isSanitizerEnabled() || typeof untrustedString !== 'string' || untrustedString === '') { |
| 13 | return untrustedString; |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * onload is fired when appending to a document |
| 18 | * fragment in Chrome. If a string |
| 19 | * contains onload then we should not |
| 20 | * attempt to add this to the fragment. |
| 21 | */ |
| 22 | if (untrustedString.includes('onload=')) { |
| 23 | return ''; |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Create a document fragment |
| 28 | * separate from the main DOM, |
| 29 | * create a div to do our work in |
| 30 | */ |
| 31 | const documentFragment = document.createDocumentFragment(); |
| 32 | const workingDiv = document.createElement('div'); |
| 33 | documentFragment.appendChild(workingDiv); |
| 34 | workingDiv.innerHTML = untrustedString; |
| 35 | |
| 36 | /** |
| 37 | * Remove any elements |
| 38 | * that are blocked |
| 39 | */ |
| 40 | blockedTags.forEach((blockedTag) => { |
| 41 | const getElementsToRemove = documentFragment.querySelectorAll(blockedTag); |
| 42 | for (let elementIndex = getElementsToRemove.length - 1; elementIndex >= 0; elementIndex--) { |
| 43 | const element = getElementsToRemove[elementIndex]; |
| 44 | if (element.parentNode) { |
| 45 | element.parentNode.removeChild(element); |
| 46 | } else { |
| 47 | documentFragment.removeChild(element); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * We still need to sanitize |
| 52 | * the children of this element |
| 53 | * as they are left behind |
| 54 | */ |
| 55 | const childElements = getElementChildren(element); |
| 56 | |
| 57 | /* eslint-disable-next-line */ |
| 58 | for (let childIndex = 0; childIndex < childElements.length; childIndex++) { |
| 59 | sanitizeElement(childElements[childIndex]); |
| 60 | } |
| 61 | } |
| 62 | }); |
| 63 | |
| 64 | /** |
no test coverage detected