Call a function on page refresh using Javascript - javascript

function warnuser()
{
return "Don't refresh the page.";
}
window.onbeforeunload = warnuser;
If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not!
I am confused about how to do that.
Thank you

You need to intercept the F5 key press and setup the onbeforeunload handler only in that case:
document.addEventListener('keydown', function(e) {
if(e.which == 116) {
window.onbeforeunload = function() {
window.onbeforeunload = null;
return "Do you really want to refresh the page?";
}
}
}, false);
Demo: http://jsfiddle.net/ejDrq/
Note that this does not work if the user clicks the Refresh button. It is impossible to intercept this.

If you have control of the server side which is hosting the page then you can handle this logically with a semaphore (wiki:semaphore). Basically it is a spinning lock which would be implemented in their server side session. Resetting the page state if they have entered and not exited in a safe manner. Naturally, as with all spinning locks, there would have to be a safe state to clear the lock out.

Related

Angular 2: Reload current page on browser back / forward / refresh

Been doing some research, is there any way to just reload the current page on user clicking the browser back button or forward? For SPA.
I know it is not recommended to restrict users from using their browser buttons and probably not much control of them either.
I was looking into something like this:
#HostListener('window:beforeunload', ['$event'])
onPopState(event) {
console.log("Back Button detected!");
window.history.forward();
}
Update: This is closer to what I want to achieve, but if the user spams the back button, he can potentially get back to a previous screen in SPA. (I am not using { skipLocationChange: true } so that may resolve that issue.
<script>
history.pushState(null, null, location.href);
window.onpopstate = function (event) {
history.go(1);
};
</script>

php/javascript prevent page reload/refresh

In my project i have a php page where i whant that in case of browser reload, or F5 the page redirect to another one.
I have insert this code:
<script type="text/javascript">
window.onbeforeunload = function() {
window.location.href = "../index.html";
}
</script>
If instead of window.location.href instruction i insert an alert("test"); the code run, but with my code in case of refresh the page cannot redirect to index.html. Why?
You can capture the F5 or CTRL+R keypresses and handle events before a redirect. Although changing any default browser behavior may be considered evil and more of an annoyance by your website users.
Here i have provided an example function to handle redirecting the user when they try to refresh the page. http://jsfiddle.net/dQEeW/
The heart of it and what handles the location change is this event binding.
$(document).bind('keydown', function( event ){
if( event !== undefined ) {
if( (event.keyCode == 82 &&
event.ctrlKey
) || (event.keyCode == 116)
) {
event.keyCode = 0;
if(destination) window.location.href = destination;
return !destination; //false if destination was set true otherwise.
}
}
});
The function was based on another SO answer but I have limited it to only handle F5 and expanded it a bit to handle CTRL+R. You can only limit the keyboard driven refreshes though.
Pulling from yet another SO answer you may want to capture page unloads and return a string, to warn the users they are trying to do something it hasn't been designed to do.
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
That should give you the opportunity to address the reason they want to leave and a chance for them to cancel it.

javascript detect if user left the site or just refreshed/clicked link

I am using a nodejs server to display online users, but it activates the disconnected function even when the user clicks a link or refreshes the page, I am trying to bypass this, by sending a message to the server only if the user closes the tab/window with the following code:
var socket = io.connect('http://example.com:8000');
socket.emit('started', { username: "TestUser", });
var clicked = false;
$(document).ready(function() {
$("a[href]").click(function() {
clicked = true;
});
$(document).bind('keypress keydown keyup', function(e) {
if(e.which === 116) {
clicked = true;
}
if(e.which === 82 && e.ctrlKey) {
clicked = true;
}
});
});
window.onbeforeunload = function(e){
if(!clicked) {
socket.emit('userDisconnected', { user: "TestUser" });
}
};
this works for if a user clicked a link and also when a user presses F5, but how can I detect if they clicked the browsers refresh button
I basically want the userDisconnected message to be sent ONLY when the user leaves my website
thanks
Not possible, and if it were it would probably be considered a bug. But what you did here is clever, looking for key events.
Depending on what you actually want to accomplish, you can approach it another way. Send a notification through your socket on every window unload. Put that socket on standby by setting a timeout event on that socket. Have your page also emit a reconnect signal on refresh or navigation within your site (something saying I'm back). If a socket on standby does not receive this signal within 5 (or some other number) seconds, close the connection on the server. If it does, cancel the timeout.

How to capture when a user is leaving ASP.Net page unexpectedly

I need to prompt a user when they are leaving my ASP.Net page unexpectedly with a message to ask if they are sure they want to leave. A post back or when the save button is clicked should not fire the warning. There are a bunch of articles covering this but I am brand new to this and appear to have got my wires crossed.
The recommended way appears to be to use the window.onbeforeunload event but behaves unexpectedly for me. This is fired when the page loads as opposed to when the page unloads.
<script language="JavaScript" type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
If I use the JQuery implementation it fires when the page unloads but the problem is it fires before the code behind is executed. So I cannot set a variable on the client saying don’t fire the event this time as it is a post back or a Save.
$(window).bind('beforeunload', function () {
return 'Are you sure you want to leave?';
});
Can anyone point me in the correct direction as I know I am making basic mistakes/miss-understanding?
Edit:
So I am nearly there:
var prompt = true;
$('a').live('click', function () {
//if click does not require a prompt set to false
prompt = false;
});
$(window).bind("beforeunload", function () {
if (prompt) {
//reset our prompt variable
prompt = false;
//prompt
return true;
}
})
Except the problem is in the above code I need to be able to differentiate between the clicks but I haven't been able to figure that out yet i.e. I am missing a condition here "//if click does not require a prompt set to false".
Any ideas?
Thanks,
Michael
You can try using this:
$(window).unload(function(){
alert('Message');
});
In case people are interested this is the roundabout solution to my problem. How to tell if a page unload in ASP is a PostBack

Check if window.onbeforeunload has been triggered by a page refresh?

I have a function like this to prompt the user to confirm they want to navigate away from the page:
window.onbeforeunload = function() {
return "You may lose any unsaved changes.";
};
Now I'd like to check whether this is a just a page refresh (F5), and not render the message in this case. Is this possible?
Thanks
Nope, that's not possible, there is no way to find out if the refresh button of browser was pressed.

Categories

Resources