From 3e652c46b3217b5d6336740fc237581656f0a24d Mon Sep 17 00:00:00 2001 From: Eoghan Murray Date: Mon, 22 May 2023 03:53:36 +0100 Subject: [PATCH] Avoid triggering a CSP (content security policy) error (#846) * Fix for #816 - avoid triggering a CSP (content security policy) error with `.setAttribute('style')` * The bare unattachedDoc that I previously naively created didn't have a doctype and wasn't a HTML document, so the child style element didn't have the `old.style` attribute available * Add a try/catch to provide some robustness in case `document.implementation.createHTMLDocument` isn't available --- packages/rrweb/src/record/mutation.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/rrweb/src/record/mutation.ts b/packages/rrweb/src/record/mutation.ts index 337394acf1..f352424b5f 100644 --- a/packages/rrweb/src/record/mutation.ts +++ b/packages/rrweb/src/record/mutation.ts @@ -472,6 +472,14 @@ export default class MutationBuffer { if (isIgnored(m.target, this.mirror)) { return; } + let unattachedDoc; + try { + // avoid upsetting original document from a Content Security point of view + unattachedDoc = document.implementation.createHTMLDocument(); + } catch (e) { + // fallback to more direct method + unattachedDoc = this.doc; + } switch (m.type) { case 'characterData': { const value = m.target.textContent; @@ -554,7 +562,7 @@ export default class MutationBuffer { } if (attributeName === 'style') { - const old = this.doc.createElement('span'); + const old = unattachedDoc.createElement('span'); if (m.oldValue) { old.setAttribute('style', m.oldValue); }