2

On tab\browser close I need to send data to server. I found this answer (based on this blog) which recommends to use sendBeacon. Here is shown how the data must be prepared in order to send them to server via Ajax. I repeated the structure from the answer:

window.addEventListener('unload', this.sendDataToServer, false)

sendDataToServer () {
    myData = JSON.stringify({
    'mutation': `mutation EmailAuth($email: String!, $password: String!) {
        getOrCreateUser(email: $email, password: $password) {
        token
        }
    }
    `,
    'variables': {email: 'test@test.net', password: 'Test'}
    })

    navigator.sendBeacon('http://localhost:8000/graphql', myData)
}

In this case Django shows: "POST /graphql HTTP/1.1" 400 53

I also found in internet the version with Blob:

window.addEventListener('unload', this.sendDataToServer, false)

sendDataToServer () {
    let headers = {
        type: 'application/json'
    }
    let myBlob = new Blob([JSON.stringify({
        'mutation': `mutation EmailAuth($email: String!, $password: String!) {
            getOrCreateUser(email: $email, password: $password) {
            token
            }
        }
        `,
        'variables': {email: 'test@test.net', password: 'Test'}
    })], headers)

    navigator.sendBeacon('http://localhost:8000/graphql', myBlob)
}

but in this case there is no any Django's reaction at all.

How can I wrap my data on a frontend side into GraphQL format and put it in sendBeacon in the way, which can be accepted by server side?

TitanFighter
  • 4,582
  • 3
  • 45
  • 73

1 Answers1

4

Found why Blob does not work, with a help of using button instead of unload. The issue is with chrome browser. Console shows: Uncaught DOMException: Failed to execute 'sendBeacon' on 'Navigator': sendBeacon() with a Blob whose type is not any of the CORS-safelisted values for the Content-Type request header is disabled temporarily. See http://crbug.com/490015 for details.

Django is waiting for request of application/json type, which according to the link from error is not safe.

For Firefox this issue can be fixed using Django's package corsheaders and add CORS_ALLOW_CREDENTIALS = True to the settings.

TitanFighter
  • 4,582
  • 3
  • 45
  • 73