如何使用(浏览器)后退按钮检测用户是否进入了页面?

时间:2014-10-30 10:24:36

标签: javascript jquery html cross-browser back

我有一些页面包含动态生成的部分视图,例如在某些搜索页面中。

如果用户使用浏览器后退按钮或后退按钮返回到此类页面,则执行如下操作:

@if (Request.UrlReferrer != null)
{
   <button onclick="history.go(-1); return false;" class="flatButtonSecondary">back</button>
}

他没有从会话或cookie中加载动态生成的输入,因为页面已从浏览器的缓存中加载。

我发现了这个类似的主题:How do I detect if a user has got to a page using the back button? 并实现了如下答案:

<form name="ignore_me">
        <input type="text" value="0" id='page_is_dirty' name='page_is_dirty' style="display: none" />
</form>

<script>
   var dirty_bit = $('#page_is_dirty')[0];
   if (dirty_bit.value === '1') window.location.reload();
   function mark_page_dirty() {
      dirty_bit.value = '1';
   }
   $(function () { mark_page_dirty(); })
</script>

在我的布局视图中的标记下,所以每次我获取页面时都会调用它。

所以这在Chrome中运行良好,但在Firefox中它运行在无限循环中,在IE 10中它什么都不做。

有没有人知道如何在所有三种浏览器中运行它,或者可以给我一个替代实现?

修改

在使用不同浏览器进行一些实验后,我发现了一个似乎适用于所有三种解决方案的解决方案(FF,IE10,Chrome)。这是:

<input type="hidden" id="page_is_dirty" value="no">
<script type="text/javascript">
    onload = function () {
        var e = document.getElementById("page_is_dirty");
        if (e.value == "no") e.value = "yes";
        else { e.value = "no"; location.reload(); }
    }
</script>

但我不确定,为什么会这样,而我的第一个版本不是。有人能够填补我的想法吗?

0 个答案:

没有答案