javascript beforeunload detect refresh versus close - javascript

Using the following function is it possible to detect which button the user has
pressed the refresh button or the close button? If not is there another way?
$(window).bind('beforeunload', function(event) {
return 'pls save ur work';
});

The simple answer is no - browsers' security models do not allow you to explicitly detect in what way a user has chosen to leave your page (refresh / close / internal link / external link).
detect refresh browser for unload/beforeunload when browser closed
It is possible - using a cookie - to check when a user loads your page whether they were previously on that site in the same session - e.g. detect if they have refreshed - but not before they refresh:
Detect Browser Refresh in Javascript
Check if page gets reloaded or refreshed in Javascript
A partial and imperfect approach would be to detect whether they pressed "F5" or "Ctrl+R" or "Cmd+R" (keyboard shortcuts for refresh) just before the page unload. This will detect some refreshes, but not where the user actually clicked the refresh button.
(function($) {
var refreshKeyPressed = false;
var modifierPressed = false;
var f5key = 116;
var rkey = 82;
var modkey = [17, 224, 91, 93];
// Check for refresh keys
$(document).bind(
'keydown',
function(evt) {
// Check for refresh
if (evt.which == f5key || window.modifierPressed && evt.which == rkey) {
refreshKeyPressed = true;
}
// Check for modifier
if (modkey.indexOf(evt.which) >= 0) {
modifierPressed = true;
}
}
);
// Check for refresh keys
$(document).bind(
'keyup',
function(evt) {
// Check undo keys
if (evt.which == f5key || evt.which == rkey) {
refreshKeyPressed = false;
}
// Check for modifier
if (modkey.indexOf(evt.which) >= 0) {
modifierPressed = false;
}
}
);
$(window).bind('beforeunload', function(event) {
var message = "not refreshed";
if (refreshKeyPressed) {
message = "refreshed";
}
event.returnValue = message;
return message;
});
}(jQuery));
You can also detect when a link is clicked whether the target of the link is on the same site or not:
How can I detect when the user is leaving my site, not just going to a different page?

Related

How to stop the page from redirecting to another page without the user action (StopPropogation) and window.oneforeunload event?

function confirmExit(e) {
var f = FormChanges(); //checking whether page has been modified or not
if (f.length > 0){
if (submitForm == false) {
if(!e) var e = window.event;
//e.cancelBubble for IE and it does work
e.cancelBubble = true;
e.returnValue = "You have made updates to this page which have not been saved.";
//e.stopPropagation for Firefox doesn't work.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
}
setTimeout("enableBeforeUnloadHandler()", "100");
}
} //ignore this
window.onbeforeunload=confirmExit;
function enableBeforeUnloadHandler()
{
window.onbeforeunload=confirmExit;
}
When the user wants to go to some other page without submitting the form in the current page,it prompts whether to leave the page or not?
But the problem is, it redirects to the other page in a couple of seconds without waiting for the user action at all,How do i fix this?
(I doesn't work in Firefox,in IE it works fine)
Could be like this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You actually need to return true (change page) or false (stay on page).

how to prevent f5 when cursor on URL

Normally we can prevent a page refresh using F5 with javascript as below
if (keyCode == 116)
event.preventDefault();
But I want to prevent the F5 refresh from working when the cursor is on the URL. This is not an application refresh, this is an in-page browser refresh.
When the cursor is on the URL and user presses the F5 key, the page will refresh. I need to prevent this.
Please help me.
You can't prevent this to happen. Once the focus on the page is lost (i.e when you click in the URL bar) javascript won't receive keyboard events anymore.
However, you can display a message to the user to warn them they are about to leave the page.
window.onbeforeunload = function(){
return "Your message here";
};
The user will be prompted the message when they try to leave the page (or refresh it) and have the option to leave or stay on the page. You can't completely stop the user from reloading, but you can make it sound real scary if they do.
You can't check if mouse cursor if on URL, but you can check if your cursor is at position [0,0]
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;
}
$(document).on("keydown", function(e){
if ((e.which || e.keyCode) == 116 && (cursorX == 0 && cursorY == 0))
e.preventDefault();
});
If cursorX and cursorY are equal to 0, then prevent your action
You can use onmouseover to keep track of when the mouse is over the URL and then you can use onmouseout to keep track of when it is off the URL. see the following example.
<a onmouseover="overIsTrue()"
onmouseout="overIsFalse() href="http://www.yourpage.com">here</a>
//keep track of the mouse state
var overURL = false;
window.addEventListener('keydown', function (event) {
// if the key is 116 and the mouseover is true
if (event.keyCode === 116 && overURL) {
// prevent default behaviour
event.preventDefault();
return false;
}
});
//mouse over is true
function overIsTrue() {
overURL = true;
}
//mouse over is false
function overIsFalse() {
overURL = false;
}

Show alert when the user click the browser back button

Iv been trying to figure out the best way to do this without much luck. I would like to do something if the user clicks back such as showing a custom dialog.
I have tried this which works to a certain extend:
var url = 'www.examples.com';
history.pushState(
{
pushStateUrl: url
},
url,
url
);
window.onpopstate = function() {
showDialog();
};
But it doesnt feel clean as it involves manipulating the browser history. Is there any better way to detect back without changing the history.
p.s. it does not have to work in all browsers. And preferably not using jquery.
Also beforeunload does not work in my case as I cannot show my own custom dialog.
this is a late response but I am posting in the intention of this could help to someone like me
add **beforeunload** event lister for your page when loaded
and remove it when submitting the form or whenever you want
step 1: var stayOnPage =function(){
confirm("Would you like to save this draft?");
if (!stayOnPage) {
history.back() or
// do your stuff
} else {
// do your stuff
}
}
window.addEventListener('beforeunload',stayOnPage);
step 2: remove event listener when you want
function onSubmitForm(){
window.removeEventListener('beforeunload',stayOnPage);
}
<button onclick="onSubmitForm()"> Submit </button>
if this doesn't work
change beforeunload to popstate
i.e
function onSubmitForm(){
window.addEventListener('popstate', stayOnPage);
}
Try this and it's found here
window.onbeforeunload = onBack;
function onBack(evt)
{
if (evt == undefined)
evt = window.event;
if ( (evt.clientX < 0) ||
(evt.clientY < 0) ||
(evt.clientX > document.body.clientWidth) ||
(evt.clientY > document.body.clientHeight)
)
{
alert('Unload from browser button press');
return "You clicked some browser button? Do you want to move away from this page?";
}
return undefined;
}

How to restrict browser back functionality caused by mouse side buttons?

I have an application which presents the user with a set of questionnaires, displayed using frames. I want to restrict the users from navigating back/forward using mouse side buttons, there are navigation buttons on each of the frames and I don't want to jeopardise the functionality of the buttons when restricting mouse side buttons.
I have already restricted the browser back functionality from keyboard using javascript, but cannot restrict mouse side buttons.
It seems that this person was having the same problem and here is the solution that was presented to him >
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}

onbeforeunload confirmation screen customization

Is it possible to create a custom confirmation box for the onbeforeunload event in a browser? I tried but then I get 2 confirmation boxes (one from me which is nothing more than return confirm... and then the standard one from the browser).
At the moment my code looks like:
var inputChanged = false;
$(window).load(function() {
window.onbeforeunload = navigateAway;
$(':input').bind('change', function() { inputChanged = true; });
});
function navigateAway(){
if(inputChanged){
return 'Are you sure you want to navigate away?';
}
}
I'm using jQuery for this.
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
Please note: Most browsers put this message after some other text. You do not have complete control of the content of the confirmation dialog.
No, you can't avoid the standard one from the browser. All you can do is inject some custom text into it; if you use the following event handler (registered the prototype lib way):
Event.observe(window, "beforeunload", function(event) {
if (showMyBeforeUnloadConfirmation)
event.returnValue = "foo bar baz";
});
(and showMyBeforeUnloadConfirmation is true) you'll get the browser's standard confirmation with the following text:
Are you sure you want to navigate away from this page?
foo bar baz
Press OK to continue, or Cancel to stay on the current page.
[ OK ] [ Cancel ]
I faced the same problem, I was able to get its own dialog box with my message, but the problems I faced were:
It was giving message on all navigations and I wanted it only for close click.
With my own confirmation message if user selects "Cancel", it still shows the browser's default dialog box.
Following is the solutions code I found, which I wrote on my Master page.
function closeMe(evt) {
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt && evt.clientX >= (window.event.screenX - 150) && evt.clientY >= -150 && evt.clientY <= 0) {
return "Do you want to log out of your current session?";
}
}
window.onbeforeunload = closeMe;

Categories

Resources