简体   繁体   中英

window.onbeforeunload listener not triggering on tab close in Firefox

The Problem

I have a function that should run on window.onbeforeunload. In Chrome, this works correctly and runs whenever a tab or window is closed or refreshed. In Firefox, however, it only runs on refresh, not close.

The Code

Here is an example:

var onStorageUpdate = function(){
    var lastUnloaded = localStorage.getItem("LastUnloaded");
    if(lastUnloaded === null){
        $("div").text("Never stored");
    }
    else{
        $("div").text(lastUnloaded);
    }
};

onStorageUpdate();

window.addEventListener("beforeunload", function(){
    var now = Date.now();
    localStorage.setItem("LastUnloaded", now);
});

window.addEventListener("storage", function(){
    onStorageUpdate();
});

Here is the order of events that should work in the above code:

  1. On initial page load, attempt to get LastUnloaded from localStorage. If nothing is retrieved, show "Never Stored", otherwise show the value that was stored (should be a long integer timestamp)
  2. Upon unloading a tab, updated LastUnloaded with the current timestamp. This is the part that doesn't seem to work in Firefox when closing a window.
  3. Upon change in localStorage, update the DOM to show the timestamp

Demo

Here is a codepen of the example: http://codepen.io/jakelauer/full/NqRyqQ/

In order to test it, open the link in two different windows or tabs. You should notice that when you refresh either tab, both tabs update to show the same timestamp. In Chrome, you will notice that if you close one tab, the other tab will update its timestamp. In Firefox, you will notice that the timestamp does not get updated .

Any ideas? Thanks in advance!

我最终只使用了onunload,它在任何地方都可以正常工作。

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