Showing posts with label refresh. Show all posts
Showing posts with label refresh. Show all posts

Tuesday, April 6, 2010

Disable Refresh in Webpage Using Javascript (F5 & Ctrl + R)

Okay here's another script for disabling refresh (F5 & Ctrl + R) in your web pages.


document.onkeydown = function() {    
    switch (event.keyCode) { 
        case 116 : //F5 button
            event.returnValue = false;
            event.keyCode = 0;
            return false
        case 82 : //R button
            if (event.ctrlKey) { 
                event.returnValue = false
                event.keyCode = 0;  
                return false
            } 
    }
}

Same as before, you can add this to your main javascript file and place it in the head part of your page.

It works by adding a function to your page's onkeydown event. Then we simply get which button was pressed by using event.Keycode (116 for F5 and 82 for R). Also, notice the "if" statement for R, it simply checks if the control button was pressed at the same time as R by checking event.ctrlKey

But there's a limitation to handling page refreshes with this code. You simply cannot control the refresh button specific to your browsers' toolbar. 



So the only way to really prevent users to refresh the page is by using this code and at the same time opening your page at a new window without the toolbar. 

Check http://codingresource.blogspot.com/2010/01/javascript-windowopen-in-net.html for more info on how to do that.

Thursday, January 28, 2010

ASP.NET C# Refresh page from code behind

To refresh your page you may use the javascript function:


window.location.reload();


For example you can use that on the OnClientClick attribute of an ASP.NET button:


<asp:button ID="btnRefresh" OnClick="btnRefresh_Click" runat="server" Text="REFRESH" 
OnClientClick="window.location.reload();" />


The code above will work fine, but if let's say you have some other server-side logic you want to run on the code for btnRefresh_Click, it won't be executed because the page would already be refreshed by then.


So to run your server-side code, first remove the OnClientClick attribute on the asp button tag above. Then place the following code inside your button click event:



protected void btnRefresh_Click(object sender, EventArgs e)
{
    //Your logic here...
    Page.Response.Redirect(HttpContext.Current.Request.Url.ToString(), true);
}


We simply redirect the page to its current url and that does the trick.



-k