如何防止在页面加载时执行 javascript 函数

How to prevent executing a javascript function on page load?

本文关键字:执行 javascript 函数 加载 何防止      更新时间:2023-09-26

我有一个本地网页来管理路由器上的 ssh 隧道,我正在尝试对我的 ssh 隧道发出实时声音通知。当它连接/断开连接时,它会播放声音。到目前为止,它运行良好,但问题是每次我加载网页时它都会播放声音,我只希望它在我的 ssh 连接/断开连接时播放声音,我不希望它在加载页面时播放声音即使它满足条件(连接/断开连接)。这是我的脚本:

var count = 0; // variable to prevent my function to play sound every second
function sshNotification() {
    $.ajaxSetup({ cache: false });
    $.ajax({
        type:"get",
        url:"cgi-bin/check", // CGI script to check whether my ssh is connected / disconnected
        success:function(data) {
            if (data.indexOf("192.168.1.1:1080")>-1) {
                if (count == 0) {
                    var audio = new Audio("on.ogg"); // Play a sound when it's connected
                    audio.play();
                    count = 1;
                };
            }
            else {
                if (count == 1) {
                    var audio = new Audio("off.ogg"); // Play a sound when it's disconnected
                    audio.play();
                    count = 0;
                };
            } 
            setTimeout(sshNotification, 1000);
        }
    });
};
sshNotification();

当我的 ssh 连接时,CGI 输出如下所示:

192.168.1.1:1080

当我的 ssh 断开连接时,它不会输出任何内容。如何播放声音通知,而不是在页面加载时播放,但仅在我的 ssh 连接/断开连接时播放。对不起,如果你认为我的解释有点混乱,请随时问你不明白哪一部分。谢谢。

因此,

如果您只想检测状态更改:

var count = 0; // variable to prevent my function to play sound every second
var lastState;
function sshNotification() {
    $.ajaxSetup({ cache: false });
    $.ajax({
        type:"get",
        url:"cgi-bin/check", // CGI script to check whether my ssh is connected / disconnected
        success:function(data) {
            if (data.indexOf("192.168.1.1:1080")>-1) {
                if (count == 0) {
                    if(lastState !== 'connected') {
                        var audio = new Audio("on.ogg"); // Play a sound when it's connected
                        audio.play();
                        count = 1;                          
                    }
                    lastState = 'connected';
                };
            }
            else {
                if (count == 1) {
                    if(lastState !== 'not_connected') {
                        var audio = new Audio("off.ogg"); // Play a sound when it's disconnected
                        audio.play();
                        count = 0;                      
                    }
                    lastState = 'not_connected';
                };
            } 
            setTimeout(sshNotification, 1000);
        }
    });
};
sshNotification();