我有一个本地网页来管理我的路由器上的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连接/断开时播放。对不起,如果您认为我的解释有点令人困惑,请随时询问您不理解的部分。感谢。
答案 0 :(得分:0)
因此,如果您只想检测状态变化:
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();