Trusted Types API violation fix

This commit is contained in:
Rafayel Hovhannisyan 2024-08-27 17:33:44 +04:00
parent 9907eb32c2
commit f69cf5ea28
2 changed files with 30 additions and 2 deletions

View File

@ -12,7 +12,7 @@ export function createStyleTag(style: string, nonce?: string, suffix?: string):
}
styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ''}`, '')
styleNode.innerHTML = style
styleNode.textContent = style
document.getElementsByTagName('head')[0].appendChild(styleNode)
return styleNode

View File

@ -14,9 +14,37 @@ const removeWhitespaces = (node: HTMLElement) => {
return node
}
let policy = {
createHTML: (input: any) => input,
createScript: (input: any) => input,
createScriptURL: (input: any) => input,
}
try {
// @ts-ignore
// eslint-disable-next-line no-undef
policy = globalThis.trustedTypes.createPolicy('tiptap', {
createHTML: (input: any) => input,
createScript: (input: any) => input,
createScriptURL: (input: any) => input,
})
} catch (error) {
// @ts-ignore
// eslint-disable-next-line no-undef
if (window.trustedTypes) {
// @ts-ignore
// eslint-disable-next-line no-undef
policy = window.trustedTypes.createPolicy('tiptap', {
createHTML: (input: any) => input,
createScript: (input: any) => input,
createScriptURL: (input: any) => input,
})
}
}
export function elementFromString(value: string): HTMLElement {
// add a wrapper to preserve leading and trailing whitespace
const wrappedValue = `<body>${value}</body>`
const wrappedValue = policy.createHTML(`<body>${value}</body>`)
const html = new window.DOMParser().parseFromString(wrappedValue, 'text/html').body