I have a local webpage to manage my ssh tunnel on my router and I'm trying to make a realtime sound notification of my ssh tunnel. When it's connected / disconnected, it plays a sound. So far it works well but the problem is that every time I load my web page it plays a sound, I only want it to play a sound when my ssh is either connected / disconnected, I don't want it to play a sound when I load my page even though it meets the condition (connected / disconnected). This is my script:
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();
The CGI output looks like this when my ssh is connected:
192.168.1.1:1080
And it outputs nothing when my ssh is disconnected. How can I play a sound notification not on page load but only when my ssh is either connected / disconnected. Sorry if you think my explanation is kinda confusing, feel free to ask which part you don't understand. Thanks.
So if you want only detect state change:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.