为什么在线和离线事件不会在 Firefox 中触发?

Why are online and offline events not firing in Firefox?

我正在尝试实现一个 JS 函数,以便在连接发生变化时被调用,换句话说,当互联网连接丢失或重新连接时。

我在 Mozilla 论坛上找到了一个这样的例子:https://developer.mozilla.org/en-US/docs/Online_and_offline_events

这是我的代码:

    $(document).ready(function () {

        window.addEventListener('offline', function () {
            alert('Internet connection lost');
        });

        window.addEventListener('online', function () {
            alert('Internet connection restored');
        });
    });

然而奇迹般地这在 IE 和 Chrome 中有效,但在 Firefox 中无效。 (在Mozilla论坛上测试也是一样)

我尝试将 onoffline/ononline 参数添加到 body 标签中,但也不成功。

我在这里遗漏了什么吗?

Firefox 对 navigator.onLine 属性有不同的解释。

如您所见here

We return false when we're in offline mode. Firefox 4 only enters offline mode if the user explicitly requests so (it's an option in the file menu). If we're not in offline mode, we will try to access the network if you try to "follow a link" or "request a remote page". So per spec, we're returning true unless we're in offline mode.

对于很多用户来说,这不是预期的行为。所以看起来他们 have already changed 它在 41.0a2 版本中。

Firefox 41 将于 2015 年 9 月发货。

所以恐怕您需要稍等片刻才能看到它的效果;)

不管怎样,我们can not rely对这个属性的要求太高了。

希望对您有所帮助!