'Is Chrome erroneously enforcing CSP when in report-only mode?
There's a script tag that is being dynamically loaded into the DOM like so,
const scriptCode = `
(function() {
var APP_ID = "${intercomAppId}";
(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',w.intercomSettings);}else{var d=document;var i=function(){i.c(arguments);};i.q=[];i.c=function(args){i.q.push(args);};w.Intercom=i;var l=function(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/' + APP_ID;var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s, x);};if(document.readyState==='complete'){l();}else if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})();
})()
`;
let intercomPolicy;
if (window.trustedTypes) {
intercomPolicy = window.trustedTypes.createPolicy("Intercom", {
createHTML: (html) => html,
});
}
const sanitizedScriptCode =
intercomPolicy?.createHTML?.(scriptCode) ?? scriptCode;
const script = document.createElement("script");
script.innerHTML = sanitizedScriptCode;
document.body.appendChild(script);
Note that the script's script is itself adding a script tag. Although I believe the error is reported on the "outer" script because it is not added to the DOM. I was hopeful that the above would be sufficient, but it's not, Chrome refuses to load this script,
This document requires 'TrustedScript' assignment. An HTMLScriptElement was directly modified and will not be executed.
Not sure if related, but the site has CSP in report only mode enabled,
content-security-policy-report-only: default-src 'none'; script-src 'self'; img-src 'self'; style-src https://fonts.googleapis.com 'self' 'unsafe-inline'; font-src https://fonts.gstatic.com; frame-ancestors 'none'; form-action 'self'; upgrade-insecure-requests; object-src 'none'; base-uri 'none'; require-trusted-types-for 'script'; manifest-src 'self'; connect-src 'self'
Firefox reports a CSP violation, but still executes the script as expected given it's in report-only mode.
Is this a bug in Chrome? Why does Chrome refuse to run the script if CSP is report only?
Chrome error:
Firefox error (but script still runs):
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


