I've 2 asp.net pages..page A and page B. On clicking a link on page A, user gets redirected to page B.When on page B, if user clicks browser's back button, I need to forcefully invoke page refresh of page A. How do I achieve this functionality? Note:Code needs to be compatible across different browsers...ie IE, firefox, opera, etc
6 Answers
I think there is no way for Javascript to tell whether it is the first visit or coming from the back button. So I put the parts of the page that need to be updated in an UpdatePanel, and then do the JavaScript to always refresh these on every page load. Not very elegant but it fixes my problem.
function addLoad(fn) { if (window.addEventListener) { window.addEventListener("load", fn, false); return true; } else if (window.attachEvent) { var r = window.attachEvent("onload", fn); return r; } else { return false; } } function refreshBack() { __doPostBack("<%= updatePanel1.ClientID %>", ""); __doPostBack("<%= updatePanel2.ClientID %>", ""); } addLoad(refreshBack); Comments
You could set a session variable on page B and check to see if that session variable exists on page A and handle it accordingly.
2 Comments
I'd say the best way to do it is telling the browser not to cache the page.
<% Page.Response.Expires = 0; %> If that doesn't work to your needs, you'd need javascript to force the refresh.
Psuedo code:
if (cookie does not exist) set cookie with 10 second expiration else if cookie exists { is cookie expired? { set new cookie refresh page } } 2 Comments
function SetCookie (name, value) { var argv=SetCookie.arguments; var argc=SetCookie.arguments.length; var expires=(argc > 2) ? argv[2] : null; var path=(argc > 3) ? argv[3] : null; var domain=(argc > 4) ? argv[4] : null; var secure=(argc > 5) ? argv[5] : false; document.cookie=name+"="+escape(value)+ ((expires==null) ? "" : ("; expires="+expires.toGMTString()))+ ((path==null) ? "" : ("; path="+path))+ ((domain==null) ? "" : ("; domain="+domain))+ ((secure==true) ? "; secure" : ""); } function getCookie(c_name) { var c_value = document.cookie; var c_start = c_value.indexOf(" " + c_name + "="); if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); } if (c_start == -1) { c_value = null; } else { c_start = c_value.indexOf("=", c_start) + 1; var c_end = c_value.indexOf(";", c_start); if (c_end == -1) { c_end = c_value.length; } c_value = unescape(c_value.substring(c_start,c_end)); } return c_value; } if (getCookie('first_load')) { if (getCookie('first_load')==true) { window.location.reload(true); // force refresh page-liste SetCookie("first_load",false); } } SetCookie("first_load",true);