How can I access document.cookie from a web worker?

Since web workers cannot access the document object, how can I access cookies in a working script?

Background

I work with Django and I need to pass the CSRF token to the AJAX message. The standard way to do this is to get the token from document.cookie and pass it as a header:

 xhr.setRequestHeader('X-CSRFToken', readCookie('csrftoken')); 

( source )

The XMLHttpRequest web workers support and it seems like they are sending a cookie to the server, but I cannot find a way to get the cookie in the script itself.

+6
source share
1 answer

Before xhr.setRequestHeader('X-CSRFToken', readCookie('csrftoken')); creates a varible to hold the cookie as follows:

 ck = readCookie('csrftoken');`Removing "var" variable "ck" becomes global. This way you can access it from outside the Web Worker.` xhr.setRequestHeader('X-CSRFToken', ck); 

In ck you have a cookie.

0
source

All Articles