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>
Related
I'm writing this piece of code to allow me to quickly search for the highlighted text on a webpage using a firefox plugin. I have the code publicly hosted here.
My function to capture the keypress ctrl+s and do the search is the following:
document.addEventListener("keydown", function(e) {
// Help came from https://stackoverflow.com/a/14562869/6897392
if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)){
text = getSelectionText();
if(text != ""){
e.stopImmediatePropagation();
e.preventDefault();
console.log(text);
openInNewTab(searches[default_search]+text);
}
}
}, false);
If I comment out the openInNewTab(searches[default_search]+text); line, which is the following function:
function openInNewTab(url) {
// Help came from https://stackoverflow.com/a/11384018/6897392
var win = window.open(url, '_blank');
win.focus();
return false;
}
It will prevent the save dialogue. However, if I leave the code in, it will prevent the save dialog in the original tab, but the new tab that it opens will pop up the save dialogue.
I have had no luck figuring out how to prevent the save dialogue from appearing in the second window, and would like some help.
Thank you!
If it's really doing what you describe, that sounds like a bug in Firefox, but you should be able to work around it by delaying your openInNewTab call very briefly:
document.addEventListener("keydown", function(e) {
// Help came from https://stackoverflow.com/a/14562869/6897392
if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)){
text = getSelectionText();
if(text != ""){
e.stopImmediatePropagation();
e.preventDefault();
console.log(text);
setTimeout(() => { // ***
openInNewTab(searches[default_search]+text);
}, 50); // ***
}
}
}, false);
Firefox's popup blocker should allow it, because it's scheduled within a user-initiated event.
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 !
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;
}
I want to prevent the default event on key #93 (select, between alt gr and ctrl right on AZERTY keyboard).
This key open context menu like right click.
I tried :
$(document).off('keydown');
$(document).off('keyup');
$(document).off('keypress');
$(document).on('keypress', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keyup', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keydown', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
Nothing works... I have always the contextmenu.
After checking for a while, I've been headed to another question similar to this one, but with a very different matter.
In any case, since the problem is the context menu, you don't even need jQuery for such, and the solution (despite it WON'T always work in firefox because the user may set it to disable such) is this one:
document.oncontextmenu = function (e) {
e.preventDefault();
return false;
}
fiddle:
http://jsfiddle.net/0kkm1vq0/3/
Works on chrome as well, and you won't need to use the keyboard listeners.
Reference: How to disable right-click context-menu in javascript
(which is really the same as key #93).
** note that this will disable the right click too **.
EDIT:
Not sure if this is cross-browser (the UPDATED code below seems to be working for both chrome and firefox, didn't try IE and others though), but the event fired by key #97 seems to be identified as 1, while the click seems to be identified as key 3, so you can just:
(function($){
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
$(document).on('keyup', function(e) {
e.which == 93 && e.preventDefault();
});
}
else {
document.oncontextmenu = function (e) {
e.which == 1 && e.preventDefault();
}
}
})(jQuery);
http://jsfiddle.net/0kkm1vq0/10/
To disable JUST the key and not the right click.
I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}