当用户在beforeunload上单击“停留”时,导航到其他页面

时间:2017-05-30 18:57:18

标签: javascript onbeforeunload window.location

我需要有办法执行以下操作:

  1. 当用户点击退出该窗口时,应询问他们是否要留下或离开
  2. 如果用户点击停留,则应将其定位到新页面
  3. 如果用户点击“离开”,则窗口应关闭
  4. 我目前有以下代码:

    string DatabaseCountMachines = "SELECT Machine, COUNT(*) total FROM completed GROUP BY Machine";
    
    MySqlConnection conDataBase = new MySqlConnection(constring);
    MySqlCommand cmdDataBase = new MySqlCommand(DatabaseCountMachines, conDataBase);
    MySqlDataReader StatsbyMachine;
    
    try
    {
        conDataBase.Open();
        StatsbyMachine = cmdDataBase.ExecuteReader();
    
        while (StatsbyMachine.Read())
        {
            this.chartMachine.Series["Series1"].Points.AddXY(StatsbyMachine.GetString("Machine"), StatsbyMachine.GetString("total"));
            this.chartMachine.Series["Series1"].CustomProperties = "PieLabelStyle=Outside";
            this.chartMachine.Series["Series1"].Label = "#LEGENDTEXT" + "#PERCENT";      
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    

    警报正确运行,但如果用户单击“停留”,则尝试导航到另一个页面会再次运行,然后再次提示您。这将陷入无限循环,直到您决定离开页面,如果您选择“停留”,您将导航到您应该导航到的页面。

1 个答案:

答案 0 :(得分:1)

当您真正希望将用户重定向到其他页面时,使用布尔标志来阻止警报:

var timeout;
var redirecting = false;
$(window).on('beforeunload', function (){
    if (redirecting) { return; }
    timeout = setTimeout(function() {
       alert('You stayed');
       redirecting = true;
       window.location.href = 'desktop/salvage';
    }, 1000);
    return "You save some unsaved data, Do you want to leave?";
});

function noTimeout() {
    alert("You're leaving!");
    clearTimeout(timeout);
}

window.unload = noTimeout;