views:

45

answers:

2

Question

How do you overwrite the refresh key with a custom javascript function? I use Prototype library, by the way.

Why

I have a video with user comments on the side. There is a button to only refresh the comments via a JS function updateComments(). During some user testing, some idiots refused to use that button to update the comments. Rather, they refreshed the entire page. This causes the video to restart, which is undesirable. I would like to overwrite the F5 key or CTRL+R to call updateComments() instead of refreshing the page.

+1  A: 

You wouldn't be able to disable the browser buttons and it would be against general UI experience. One possibility would be to check how the page is loaded and display a 'Please don't do that to load comments' to the user. For example, in Google Chrome you can check if the page has been reloaded:

if (chrome.loadTimes().navigationType === 'Reload') {
  alert('Please reload comments using the magic button');
}

I'm not certain if other browsers have similar functions available but I doubt it would in many.

Generally though, my advice in this instance would be to change how you load the comments. For example, a Twitter search will periodically check for new tweets and then display a "Show X more tweets" button that the user can press to display them.

Jonathon
+1  A: 

I think the best you could do is to add a handler to the window.onbeforeunload event.

Something like this:

function beforeUnload() {
    if (videoIsPlaying) {
        return "Are you sure you want to stop the video?";
    }
}
window.onbeforeunload = beforeUnload;

Take a look at the examples here and here

Gabriel McAdams