How to detect if a user has gone to a page by using the (browser) back button?

99封情书 提交于 2019-12-10 21:25:40

问题


I have some pages with dynamic generated partial views, for example in some search pages.

If a user returned to such pages with the browser back button or with a back button implemented like:

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

He doesn´t get the dynamic generated inputs loaded from the session or cookies because the page becomes loaded out of the cache of the browser.

I found this similar thread: How do I detect if a user has got to a page using the back button? and implemented the answer like:

<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>

under the tag in my layout view so it is called every time I get the page.

So this works fine in Chrome but in Firefox it runs in an endless loop and in IE 10 it just does nothing.

Does anybody have an idea how to run this in all three browsers, or can give me an alternative implementation?

Edit:

After some experiments with the different browsers I found a solution that seems to work in all three (FF, IE10, Chrome). Here it is:

<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>

But I´m not sure, why this is running, and my first version is not. Is someone able to fill this gap in my mind?

来源:https://stackoverflow.com/questions/26650496/how-to-detect-if-a-user-has-gone-to-a-page-by-using-the-browser-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!