简体   繁体   中英

Window.onbeforeunload not setting after page refresh

I'm making an error reporter that captures errors, then just before the user refreshes/closes, it will send the errors to the server to be put in a log file. I have a window.onerror function that captures the errors and stores it in an array. Inside the window.onerror function, I also set window.onbeforeunload, which will send ask for the.network request data from the service worker (which keeps a record of the.network logs from that page load). When ctrl-f3 (on chromebook, equivalent to ctrl-f5 on windows), then try to reload it will ask confirmation to refresh the page. If I do, then try to refresh it again it won't show the popup. I did some debugging to see that window.onbeforeunload at that time is not there. In fact, the part of my code (posted below), doesn't execute! I put the error-reporting script as an external file and load it in the <head> tag of my HTML page. It is wrapped around an anonymous function, with no onload listener. Why isn't this working? I can't wrap my head around the solution, so I would gladly accept help. Thanks.

Oh, almost forgot: Here's my code (shortened to the points that are relevant to the question):

window.onerror = function(eventOrMessage, url, lineNumber, colNumber, error){
    window.onbeforeunload = function(){
      const channel = new BroadcastChannel("net-log");
      channel.postMessage({requestLog:true});
      channel.addEventListener("message",function(event){
        if(event.data.encodedLogEntries){
          console.log(event.data.encodedLogEntries);
        }
      });
      return "Sending messages";
    };
    //works the first time, then doesn't set. Actually, the second time it doesn't execute this at all!
    console.log(window.onbeforeunload);
}

I found out the problem, it was an error in my service worker for some reason causing the dilemma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM