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 !
Related
I've been having troubles with the Control + S button, I would like to remap the Control + S button to something else instead of the save page as window.
** I know that its not possible to disable it**
I want the functionality like what https://www.hastebin.com/ has, where if you control + s it does an action. I've already tried
$(window).keypress((e) => {
if (!(e.which == 115 && e.ctrlKey) && !(e.which == 19)) return true;
console.log('bruh');
e.preventDefault();
return false;
});
That DOES work, but the save as page still shows up, where as on hastebin, it does not when you do ctrl + S
Any ideas?
Use keydown rather than keypress:
$(window).on("keydown", (e) => {
if (e.key === "s" && e.ctrlKey) {
console.log("Ctrl+S");
e.preventDefault();
}
});
<div>Click here, then press Ctrl+S</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In that example I've used the key property rather than the deprecated which property, but if you need to support obsolete browsers you could use which (perhaps as a fallback).
CTRL+S fires keydown event, not keypress event AFAIK.
$(window).on("keydown", (e) => {
if (e.key === "s" && e.ctrlKey) e.preventDefault();
});
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.
I am trying to prevent page refresh only when user clicks Ctrl with R.
I try with the preventDefault() method as following but it does not work:
function disableCtrlR(s) { if ((s.which || s.keyCode) == 17 && (s.which || s.keyCode) == 82) s.preventDefault(); };
$(document).ready(function(){
$(document).on("keydown", disableCtrlR);
});
Any help on this will be appreciated. Thanks.
PS. I know this is not an ideal solution but this is the only solution for me to solve the bug on my webpage while waiting for the bug to be resolved.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on("keydown", function(e) {
e = e || window.event;
if (e.ctrlKey) {
var c = e.which || e.keyCode;
if (c == 82) {
e.preventDefault();
e.stopPropagation();
}
}
});
});
</script>
<h1>If you click in here, you won't be able to refresh with Ctrl+R</h1>
<input type="text" />
Using jQuery 2.1.1, this will disable reload by Ctrl+R
To check if there is a control key pressed simultaneously in an key event, you'll check for the KeyboardEvent.ctrlKey property.
// beware ES6 below, will fail in Netscape
onkeydown = e => {
if(e.key === 'r' && e.ctrlKey){
e.preventDefault();
console.log('ctrl + r')
}
}
<input autofocus>
Addendum:
As you mentioned in your question, this is very-much "not an ideal solution". Blocking default browser behavior should be made only on special cases, like here blocking the ctrl+R shortcut should only be done on some part of a web-application that really needs this shortcut, and not on the document itself. That's part of why I never talked about blocking the page refresh in this answer (which would need some extra work to work in this intent on all platforms).
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>
I'm attempting to create a Greasemonkey script that can submit a tweet when a user hits the 'enter' key. I've gotten this to work fine on a simple HTML page (with the help of a few excellent tips on this site). However, when I try to use the code on my twitter page, the alert only fires if a tweet is not currently being authored.
document.onkeyup = function(event){
var keyCode;
if (window.event) // IE/Safari/Chrome/Firefox(?)
{
keyCode = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyCode = event.which;
}
if (keyCode == 13){
alert("Enter pressed");
}
}
My next thought was to test for a more specific keypress event. So I tried testing for a key event within the new tweet textarea:
document.getElementsByClassName("twitter-anywhere-tweet-box-editor")[0].onkeyup = function(event)
...but this event never seems to fire. I also tried grabbing the element by tag:
document.getElementsByTagName("textarea")[0].onkeyup = function(event)
...but not dice there either. I wonder if this has to do with the fact that the new tweet window is not loaded from the get-go at window.onload(). Thoughts?
I got it thanks to this post. I've also posted the full Greasemonkey script here.
setInterval (function() { checkForTweetbox (); }, 500);
function checkForTweetbox () {
var tweetbox = document.querySelector ('div.tweet-box textarea'); //check for new tweet window
if (tweetbox) {
if (! tweetbox.weHaveProcessed) {
tweetbox.weHaveProcessed = true;
// alert ('New tweet-box found!');
}
}
tweetbox.onkeydown = function(event){
if(event.keyCode == 13){ //13 = Enter keycode
document.querySelector ('a.primary-btn').click(); //there must be at least one character in the textarea
}
}
}