When dynamically appending script into iframe, Content Security Policy isn't updated

40 Views Asked by At

I want to dynamically append a script tag into my website.

The src needs to be dynamic, where a variable determines what subdomain to request the script from. Due to the unique nature of my site, This is my CSP policy:

Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-eval' 'self'; frame-ancestors 'none'; worker-src 'none'; navigate-to 'none';

I am trying to add a script, using this code:

let subdomain = // my logic

let my_frame = document.createElement("iframe");
my_frame.csp = "script-src *.example.com";
document.body.appendChild(my_frame);

my_frame.contentWindow.document.write(`<script src="//${subdomain}.example.com"></script>`);

This code errors out:

cant load script because it violates CSP directive unsafe-eval

From what I understand about CSP, more restrictive directives take precendence. Since script-src *.example.com is more restrictive than unsafe-evaland self, my subdomain should be allowed. I will never use example.com alone, so I have only added the directive for the subdomain.

What is going wrong here?

Note: I cannot change the current Content Security Policy.

0

There are 0 best solutions below