如果用户正在使用网络,则显示可见的警报

Display an alert visible if the user is using the web or not

我是编程新手,我正在寻找一种方法来在用户是否在网络时显示警报。我已经尝试使用 alert()(http://www.w3schools.com/jsref/met_win_alert.asp 中的那个)使用计时器对其进行测试,但警报仅显示在选项卡中,而不显示在桌面上的每个应用程序 运行 上。

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display an alert box.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("Hello! I am an alert box!");
}
</script>

</body>
</html>

如果有其他语言的解决方案,我愿意尝试。 谢谢。

根据您分享的 link,如果您希望通过浏览器在任何桌面应用程序上弹出一个窗口,请使用 W3C 通知 API。例如

window.onload = function () {
    if (Notification.permission !== "granted")
        Notification.requestPermission();
};

function notifyMe() {
    if (!Notification) {
        alert('Desktop notifications not available in your browser. Try Chromium.'); 
        return;
    }

    if (Notification.permission !== "granted")
        Notification.requestPermission();
    else {
        var notification = new Notification('Notification title', {
            icon: 'Notification icon',
            body: "Notification body",
        });

        notification.onclick = function () {};
    }
}

并使用导航器在线变量调用 notifyMe()。例如

setInterval(function () {
    if (navigator.onLine)
        notifyMe();
}, 1000);

这将每 1 秒检查一次用户是否连接到互联网,如果是则显示一个弹出窗口。

https://developer.mozilla.org/en/docs/Online_and_offline_events