how to prevent f5 when cursor on URL - javascript

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;
}

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).

Disable browsers' back button, completely

Need to prevent users going to the previous page, completely.
When I use the following code it works but it's not what I need exactly. When pressing the back button it says "Document Expired":
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Another idea - to open a new window without toolbar:
<script>
function PopupWithoutToolbar(link) {
var w = window.open(link.href,
link.target || "_blank",
'menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,dependent,width=800,height=620,left=0,top=0');
return w ? false : true;
}
</script>
yahoo
But, still... If the user presses the backspace button on a keyboard he can go back. It seems that this approach is only for hiding and not disabling buttons.
Is there any way to simply ignore the back button?
I am not entirely sure if this will work, but you can try handling the event with javascript.
Like if you want to entirely disable the backspace button from allowing users to go back you can do like
$(window).on("keypress", function (e){
if(e.keycode == "backspace")
e.preventDefault();
})
I could figure out the keycode for backspace for you , but that isn't too hard to figure out. Also this uses jquery, but you can use just raw javascript. just wasn't sure what it would be offhand.
I'm using a slightly different solution:
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
}
Based on your post it sounds like your only issue is disabling the backspace button from allowing the user to go back.
Here's what I do for that using jquery. Still allows backspace to work inside enabled text editing inputs, where it should.
// Prevent the backspace key from navigating back.
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8) {
var d = event.srcElement || event.target;
if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' ||
d.type.toUpperCase() === 'PASSWORD' ||
d.type.toUpperCase() === 'FILE')) ||
d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
}
else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
}
});
Simplest thing ever:
window.onhashchange = function (event) {
//blah blah blah
event.preventDefault();
return false;
}
You can handle the location domain etc from that (window.location) then cancel the event if you want in this case.
How to Detect Browser Back Button event - Cross Browser
To disable the back button in the browser you can use use the following code in your JavaScript on the page on which you want to disable the back button.
<script>
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
</script>

How to disable Warning by "onbeforeunload" when "reload" same page?

My code works well, but I do not need this "beforeunload warning" when reloadind same page (reload button ou F5 key) , or when a click in the "back" button...
My original working code:
<script>
window.onbeforeunload = function (e) {
var msg = '\n\n\nARE YOU SURE?\n\n\n';
e = e || window.event;
if (e)
e.returnValue = msg;
//some extra conditions
document.getElementById("popUpOut").style.display = 'block';
return msg;
}
</script>
So, this is my question: How to disable beforeunload in these situations ("back button" and "reload page)?
You can't do that. A page refresh is like navigating away and unloading the DOM so the onbeforeunload event will always be called but you can prevent it using jquery for keys pressed for Ctrl + R or F5 and Backspace.
For Ctrl + R use this:
$(document).keydown(function (e) {
if (e.keyCode == 65 && e.ctrlKey) {
e.preventDefault();
}
});
For F5 use this:
$(document).keydown(function (e) {
if (e.which || e.keyCode) == 116) {
e.preventDefault();
}
});
First of all, let me say that, ""I do not want"" stop reloading the page! BUT controll the beforeunload message!
So if you allow me, I will try to explain:
A) I just want do DECIDE in that event I show (or not) the "warning
exit message"
As far everyone say to me that, "it is impossible" do control UnbeforeUnload event, I make some tests and depending of the browser it is perfecty possible, BUT this is a "working progress rechearch"
So I know this:
1) listening the keyboard it's very easy to "chose the event" and,
what I want do show in the "warning mewssage" for each one.
2) Listening the history I can chose what happends on "Navigator's
Back button", dand do the same.
3) The code below works fine in chome...
And to control the keyboard, I have this, very simple code in JS:
document.onkeydown = KeyCheck;
function KeyCheck(e) {
var key = (window.event) ? event.keyCode : e.keyCode;
if(key==116) {flag_beforeunload=false;}
if(key==8) {flag_beforeunload=false;}
if (e.keyCode == 82 && e.ctrlKey) {flag_beforeunload=false;}
document.getElementById("container").innerHTML = "key = "+key + " - " + flag_beforeunload;
}
window.onbeforeunload = function(e){
var msg = 'You are sure to exit?';
e = e || window.event;
if(e)
if (flag_beforeunload == true) {
return msg;
}
}
Following, here (dotnsf site) is where I get the code for control the browser's "back button and"... I can even disable it.
but it is en Jquery, following is my code, but in JS:
window.onpopstate = function(event) {
window.history.back(-1)
if( !event.state ){
//the to lines below, disable the back button
// history.pushState( "nohb", null, "" );
// return;
// the following line iIcan use to control the envent, in UnBeforeUnload
// flag_beforeunload=false;
}
}
}
And finaly, this is my question:
I apreciate more help, and solutions for others navigators than Chrome!
Thanks a lot !

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;
}

javascript beforeunload detect refresh versus close

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?

Categories

Resources