skip to main |
skip to sidebar
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.
Here's an example on how to popup a new window using javascript in .NET. First we'll use a simple button as the trigger source for the popup.
<asp:Button ID="btnPopup" runat="server" />
Then on the page load in the code behind, add an onclick attribute to the button.
protected void Page_Load(object sender, EventArgs e)
{
btnPopup.Attributes.Add("onclick", "window.open('http://" + Page.Request.Url.Authority + "/TestPage.aspx','Test','status,toolbar,location,menubar,directories,resizable,scrollbars,width=400,height=400')");
}
The Page.Request.Url.Authority in the code above will retrieve the root url of your site. Then just add the name of the aspx file to popup after the forward slash (if it is within another directory, just add the directory name before the aspx file, and so forth).
To explain the javascript part, window.open() accepts 3 parameters: the url of the site to popup, the window name (not title, the title should be in the head part of the new page, so make sure it doesn't have spaces), and window features.
Here's some of the commonly used window features:
status:
toolbar:
location:
menubar:
directories:
resizable: window can be resized
scrollbars:
width: the width of the window in pixels
height: the height of the window in pixels
To use these features simply add them to the list like this:
"window.open
('http://www.testpage.com','Test','status,toolbar,location,menubar,directories,resizable,scrollbars,width=400,height=400')"
If not then simply omit them:
"window.open('http://www.testpage.com','Test','width=400,height=400')"
That's it, one note though, make sure that the aspx page in the url exists or you'll get an error.
-k