Need authorization in a navigator.sendbeacon()
Asked Answered
N

2

8

My problem is that when i call a function who listen to the event onBeforeUnload(), i want to post a data. The problem is that my request is unauthorized. I need to add my bearer somewhere, but i don't know how.

Here my actual code:

@HostListener('window:beforeunload', ['$event'])
  onBeforeUnload(): void {
     navigator.sendbeacon(`${localhost:8080/apiRest}`, infoIWantToSent);
  }

For now, the request send a 401:unhautorized, which is normal, since i don't transmit any bearer.

Nelidanelie answered 14/5, 2019 at 13:44 Comment(0)
N
11

I find this solution :

@HostListener('window:beforeunload', ['$event'])
  onBeforeUnload(): void {
   fetch('url', {
        keepalive: true,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(infoIWantToSent),
      });
}

Aparently, if we must use a token connexion, we can't use navigator.sendbeacon() https://w3c.github.io/beacon/#sec-sendBeacon-method It work for almost all the cases, but not when i close an iframe which contains my page.

Nelidanelie answered 16/5, 2019 at 13:16 Comment(0)
I
2

Try this:

  let headers = {
    Authorization: 'Bearer ' + token
  };
  let blob = new Blob([JSON.stringify(infoIWantToSent)], headers);
  navigator.sendBeacon('url', blob);
Illmannered answered 14/5, 2019 at 14:1 Comment(2)
Thank you for you response. Unfortunaly, I have this error in compilation with your method : error TS2559: Type '{ Authorization: string; }' has no properties in common with type 'BlobPropertyBag'. I tried to add a type lyke this ``` const headers = { type: 'application/json', Authorization: 'Bearer ' + this.getUser().token }; ``` But it's ot working either.Nelidanelie
I would have said to include ` type: 'application/json'`, but since you have tried it already, I don't have anymore input. Sorry. Let me know the solution once you crack it. All the bestIllmannered

© 2022 - 2024 — McMap. All rights reserved.