How do I determine if a user has navigated to a page using the (browser) back button?

I have several pages with dynamically generated partial views, for example on some search pages.

If the user returned to such pages using the Back button or using the Back button, such as:

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

      

It doesn't receive dynamically generated inputs loaded from session or cookies because the page is being loaded from the browser cache.

I found this similar thread: How do I determine if a user has hit a page using the back button? and followed an 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 gets called every time I get the page.

So this works fine in Chrome, but in Firefox it runs in an infinite loop, and in IE 10 it just doesn't do anything.

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

Edit:

After experimenting a bit with different browsers, I found a solution that works in all three (FF, IE10, Chrome). Here he 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 works and my first version doesn't. Can someone fill this gap in my mind?

+3


source to share





All Articles