Failed to execute 'fetch' on 'WorkerGlobalScope'

I'm trying to pass variables from background.js file to views.py in Django. I tried many ways to do it and I write the following code, it seems to work but I stuck with this error. I searched a lot for a solution but I didn't found anything yet

//background.js

fetch("http://127.0.0.1:8000/my_app/views")
    .then(response => response.text())
    .then(responseText => {
        // Extract the X-CSRF-TOKEN cookie from the response
        let csrfToken = getCookieValue(responseText, "csrftoken");

        // Set up the data to send to the server
        let data = {
            variable1: "value1",
            variable2: "value2"
        };

        // Make the request to the server with the X-CSRF-TOKEN header
        fetch("http://127.0.0.1:8000/my_app/views", {
            method: "POST",
            body: JSON.stringify(data),
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": csrfToken
            }
        })
            .then(response => response.json())
            .then(responseData => {
                console.log(responseData);
            });
    });

// Helper function to extract a cookie value from a string
function getCookieValue(text, name) {
    let start = text.indexOf(name + "=") + name.length + 1;
    let end = text.indexOf(";", start);
    if (end === -1) {
        end = text.length;
    }
    return text.substring(start, end);
}

the error is the follwing:

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Invalid value

please help me..

Back to Top