A CSP response header is set on the web worker JS file, but it is not enforced by the browser. The CSP is enforced in the Web worker only if the parent document's response header contains the CSP header. Is this expected?

  1. index.html

        var worker = new Worker('/worker.js');
    worker.addEventListener('message', function(e) {
      console.log('Worker said: ', e.data);
    }, false);
  2. worker.js

    self.addEventListener('message', function(e) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
              self.postMessage("done by worker");
           // Typical action to be performed when the document is ready:
        } else if (this.readyState == 4 && this.status != 200) {
            self.postMessage("done by worker error");
    xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
    }, false);

Response Header Content-Security-Policy: connect-src 'self'; is set on the worker.js file, but the CSP is still not enforced and the API call is successful in the network tab.


1). Yes, this behavior is expected. If a (parent)frame does not include a CSP header, the CSP on the children will not be enforced.

2). Furthermore, if you have an XSS vulnerability, the attacker can insert frames that do not contain CSP and still run the JS [according to the above statement, the JS is inside the frame which does not contain CSP].

  • Do you happen to have a source to support (1)? I might well be mistaken but I was under the impression that the rules work differently in web workers as documented here.
    – AlphaD
    May 13 '20 at 9:14
  • 1
    @AlphaD - "However, if the script constructs a worker, code running in the worker's context will be allowed to use eval()." Your code above constructs a worker.
    – paj28
    May 13 '20 at 13:13
  • @paj28 - I read it as "(web workers) are not governed by the document's content security policy" and it also gives advice to attach the CSP directly on the worker script header which the OP has done. This answer seems to indicate that if the parent doesn't have it's own CSP it won't work. Maybe I'm just reading this wrong.
    – AlphaD
    May 14 '20 at 3:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.