Failed to execute 'parseFromString' on 'DOMParser': This document requires 'TrustedHTML' assignment (SweetAlert2/Google Sheets)

158 Views Asked by At

I have a script on Google Sheets using SweetAlert2 which was working perfectly fine till Google implemented TrustedScriptURL/TrustedHTML requirement, I have tried lot of thing but I'm not able to make it work again, can someone please help me on this?

I've read this: https://copyprogramming.com/howto/this-document-requires-trustedscripturl-assignment-in-google-sheets

As well as many others sources but still not getting it to work, so far I've this:

const createPolicy = trustedTypes.createPolicy("forceInner", {
  createHTML: (string) => string,
  createScriptURL: (string) => string,
});
const script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.src = createPolicy.createScriptURL(
  "https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.js"
);
document.head.appendChild(script);

I've also tried something like this:

let createPolicy = trustedTypes.createPolicy("forceInner", {
  createHTML: (string) => string,
  createScriptURL: (string) => string,
});

let script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.src = createPolicy.createScriptURL(
  "https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.js"
);
document.head.appendChild(script);

script.setAttribute("type", "text/javascript");
script.src = createPolicy.createScriptURL(
  "https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"
);
document.head.appendChild(script);

createPolicy = trustedTypes.createPolicy("forceInner", {
   createHTML: (string) => DOMPurify.sanitize(string, {RETURN_TRUSTED_TYPE: true}),
   createScriptURL: (string) => DOMPurify.sanitize(string, {RETURN_TRUSTED_TYPE: true}),
   createScript: (string) => DOMPurify.sanitize(string, {RETURN_TRUSTED_TYPE: true})
});

But in any case, whenever I try to test it with:

Swal.fire()

or

script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.innerText = createPolicy.createScript("Swal.fire('Hello World')");
document.head.appendChild(script);

Still throw errors due to "TrustedHTML" from the loaded "sweetalert2.js".

Screenshot Reference 1
Screenshot Reference 2

(I'm using the SweetAlert2 non-minified version just to be easier to see the lines causing the problem)

I appreciate any help to get this working once again.. Thanks.

0

There are 0 best solutions below