0

When close a tab or browser, you need to send the data in the form to Vue. It is made through mounted or created and window.addEventListener("beforeunload", this.unload). Sending failed. When I tried to check the availability of the function, I got "undefined"

mounted() {
    window.addEventListener("beforeunload", this.unload);
}
methods: {
    unload () {
      console.log("START UNLOAD FUNC");
      console.log('start sync');
      this.test;
      console.log('finish sync');
    },
    test() {
      console.log("START TEST");
    },
}
I get the following in the log:
[1006/114208.084:INFO:CONSOLE(1)] "START UNLOAD FUNC"
[1006/114208.084:INFO:CONSOLE(1)] "start sync"
[1006/114208.084:INFO:CONSOLE(1)] "finish sync"

How can data be sent when the browser is closed?

Sergey Ka
  • 25
  • 7
  • Data sent where? – null Oct 18 '21 at 09:24
  • Instead of the test function, there is a function in unload with axios post. But also the func "test" doesn't run – Sergey Ka Oct 18 '21 at 10:28
  • 1
    Maybe you are missing some brackets. Try `this.test();` – Trio Oct 18 '21 at 10:55
  • Does this answer your question? [Warn user before leaving web page with unsaved changes](https://stackoverflow.com/questions/7317273/warn-user-before-leaving-web-page-with-unsaved-changes) – tauzN Oct 18 '21 at 11:28
  • Axios in the func "test". The test function is running, but no data sent. code and log: https://pastebin.com/HkQS5KYe – Sergey Ka Oct 19 '21 at 17:22

1 Answers1

0
let body = this.body;
      
let headers = {
        type: 'application/json'
};
let blob = new Blob([JSON.stringify(body)], headers);
navigator.sendBeacon('http://127.0.0.1:8000/form/', blob);

This work for me

Sergey Ka
  • 25
  • 7