簡體   English   中英

JavaScript和瀏覽器的后退/前進按鈕

[英]JavaScript and the browser's back/forward button

我有一些JavaScript,如果ASP.NET的Session存在值,它會顯示通知。 這可能不是我現在正在學習的最佳解決方案,但是下面是代碼:

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函數中進行檢查,但這不起作用。

是否有跨瀏覽器的方式可以解決此問題?

好吧,對於初學者來說,您必須避免客戶端的導航緩存(通常,后退/前進實際上並不會拉回頁面)。

經過這一障礙后,您可以(具有諷刺意味的)使用會話變量來存儲是否已被查看[輸出],並且僅將其轉儲到頁面一次。

如果這看起來太多了,您可以在函數中添加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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM