Call a POST request to register from the unload window

I struggled to write code that reliably executes a POST request when closing a tab window. Navigator.sendBeacon seems to be exactly what I need (I only require this to work in Google Chrome).

 $(global).bind('unload', function () { let body = { UserEmail: appState.user.email, Job: { Id: appState.jobId }, Timestamp: '/Date(' + new Date().getTime() + ')/', EventOrigin: 'PdfReviewClient', Event: 'JobClosed' }; let headers = { Authorization: `JWT ${authenticationState.token}`, 'Content-Type': 'application/json; charset=utf8' }; let blob = new Blob([JSON.stringify(body)], headers); navigator.sendBeacon(configuration.rootApiUrl + 'jobevents', blob); }); 

My beacon includes custom headers, so I am creating Blob.

However, this request does not seem to be happening. This is especially difficult to debug as the window closes. So the question is, why is my lighthouse not sent?

+5
source share
2 answers

The problem was the only headline you could set with navigator.sendBeacon is Content-Type, and you set it by setting type in the Blob option. The server route had to be changed to satisfy the request without an authorization header (I passed it as a URL parameter instead - strange for a POST request, but apparently the only way to do this with a beacon). Here's what it looked like at the end:

 $(global).bind('unload', function () { if(appState.jobId == null) return; let headers = { type: 'application/json' }; let jobEventLoggingBody = { UserEmail: appState.user.email, Job: { Id: appState.jobId }, Timestamp: '/Date(' + new Date().getTime() + ')/', EventOrigin: 'PdfReviewClient', Event: 'JobClosed' }; let jobEventLoggingUrl = `${configuration.rootApiUrl}jobevents?jwt=${authenticationState.token}`; let jobEventLoggingBlob = new Blob([JSON.stringify(jobEventLoggingBody)], headers); navigator.sendBeacon(jobEventLoggingUrl, jobEventLoggingBlob); }); 

See also this question , which specifically relates to the sending of headers in beacons.

+4
source

I do not know if this can help you. You can use this for debugging.

 function logData() { var newWindow = window.open(); newWindow.document.write("ohai"); } window.addEventListener("unload", logData, false); 
0
source

Source: https://habr.com/ru/post/1263021/


All Articles