【问题标题】:How to prevent executing a javascript function on page load?如何防止在页面加载时执行 javascript 函数?
【发布时间】:2016-03-13 15:06:08
【问题描述】:

我有一个本地网页来管理我的路由器上的 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 连接/断开连接时播放。对不起,如果您认为我的解释有点令人困惑,请随时询问您不明白的部分。谢谢。

【问题讨论】:

  • if (data.indexOf("192.168.1.1:1080")>-1) 是否如您所愿?总是正确的?
  • 不,并非总是如此,当我的 ssh 断开连接时,cgi-bin/check 在触发 else 部分时不会输出任何内容。

标签: javascript jquery audio ssh


【解决方案1】:

所以如果你只想检测状态变化:

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();

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 2020-08-15
    • 2020-05-16
    相关资源
    最近更新 更多