【问题标题】:JavaScript and the browser's back/forward buttonJavaScript 和浏览器的后退/前进按钮
【发布时间】:2013-07-31 05:04:31
【问题描述】:

如果 ASP.NET 的 Session 中存在值,我有一些 JavaScript 会显示通知。这可能不是我现在正在学习的最佳解决方案,但这里是代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if (Session["Alert"] != null)
        {
            Page.ClientScript.RegisterStartupScript(GetType(), "alert", Session["Alert"].ToString());
            Session["Alert"] = null;
        }
    }
}

Session["Alert"]具有显示通知的JS功能:

Session["Alert"] = "showAlert('test')";

function showAlert(msg) {
    alert(msg);
}

如果已为其分配了值,则代码会成功运行并显示通知。单击浏览器的后退按钮,然后单击前进按钮会再次显示警报,因为页面没有经历其生命周期。

如何防止提醒显示不止一次?我尝试添加一个全局 JavaScript 变量,例如 var alertShown = false; 并在 showAlert 函数中检查它,但这不起作用。

有没有跨浏览器的方法可以解决这个问题?

【问题讨论】:

    标签: javascript asp.net http browser cross-browser


    【解决方案1】:

    好吧,对于初学者来说,您必须避免使用客户端的导航缓存(通常后退/前进实际上不会将页面拉回)。

    过了这个障碍后,您可以(讽刺地)使用会话变量来存储它是否已被查看 [输出],并且只将其转储到页面一次。

    如果这看起来太多了,您可以在函数中添加一个 cookie 检查,这样当它运行(并重新运行)时,它会检查一个 cookie,如果不存在,则会发出警报并设置一个 cookie。伪代码:

    function showAlert(msg){
      if (cookie[msg] == null){ // a cookie doesn't exist for this msg
        alert(msg); // alert the msg
        cookie[msg] = true; // set the cookie so the next pass is ignored
      }
    }
    

    【讨论】:

    • 感谢您的信息。我认为饼干是要走的路。我将看看如何使用 JS 获取/设置 cookie。
    猜你喜欢
    • 2017-06-29
    • 2011-07-28
    • 2014-05-10
    • 2023-03-08
    • 2011-06-17
    • 2015-08-07
    • 1970-01-01
    • 2011-01-08
    • 2014-04-17
    相关资源
    最近更新 更多