gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:33:28 26 4
gpt4 key购买 nike

我有一个本地网页来管理路由器上的ssh隧道,我正在尝试对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();

关于javascript - 如何防止在页面加载时执行JavaScript函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35971845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com