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;
Related
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>
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;
}
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave the page. All data will be lost!';
if (typeof evt === 'undefined') {
evt = window.event;
}
if (evt && !($("#a_exit").click)) {
evt.returnValue = message;
}
return message;
};
I want user to leave the page clicking to the link (has id ="a_exit") only. In other circumstances such as refreshing the page, clicking another link, user will be prompted that if he/she wants to leave the page. I have tried to use the code above. It still asks me if I want to go away when I click the exit link.
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').live('click',function() {
$(window).unbind('beforeunload');
});
Above works for me
My quick example of the conditional prompt before leaving page:
window.onbeforeunload = confirmExit;
function confirmExit(event) {
var messageText = tinymce.get('mMessageBody').getContent();
messageText = messageText.trim();
// ... whatever you want
if (messageText != "")
return true;
else
return void (0);
};
It works under Chrome, FF.
You can return null when you do not want the prompt to show. Tested on Chrome 79.
window.onbeforeunload = () => {
if(shouldPrompt){
return true
}else{
return null
}
}
BTW modern browser no longer support custom onBeforeUnload promp text.
It will always prompt you if you want to leave the page. It's a security issue and cannot be worked-around.
Moreover, anything you return in the onbeforeunload event handler that is not void will be treated as the message for the prompt. Refer to this article: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
This worked for me.
window.onbeforeunload = function(){
if(someBoolean) {
return 'message'
}else{
window.onbeforeunload = null;
}
}
You could just remove window.onbeforeunload in the click handler.
How about a variable to decide, if the link was clicked?
var exitClicked = false;
$("#a_exit").click(function() {
exitClicked = true;
});
window.onbeforeunload = function(evt) {
//...
if(evt && !exitClicked) {
evt.returnValue = message;
}
//...
};
You only set exitClicked = true when the link was really clicked and afterwards, before unloading you can simply check this variable.
This is quite old but I wanted just to change the code given that .live is no longer working in Jquery. So, the updated version would be:
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').on("click", function(){
$(window).unbind('beforeunload');
});
I have set up in javascript:
var onBeforeUnloadFired = false;
window.onbeforeunload = function (sender, args)
{
if(window.event){
if(!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
window.event.returnValue = 'You will lose any unsaved changes!'; //IE
}
}
else {
return 'You will lose any unsaved changes!'; //FX
}
windows.setTimeout("ResetOnBeforeUnloadFired()", 1000);
}
function ResetOnBeforeUnloadFired() {
//Need this variable to prevent IE firing twice.
onBeforeUnloadFired = false;
}
I'm trying to achieve an edit screen where the user is warned before navigating away. It works fine except I get the pop up for normal post backs of button clicks. I'm hoping to avoid this so I'm figuring if I could determine which button was pressed it would work.
Does anybody know how to determine which button was pressed in the windows.onbeforeunload?
Alternatively anyone know a better approach to what I'm trying to achieve?
Solved this by putting into an update panel all edit items TextBoxes etc.
Now the windows.onbeforeunload only fires for components external to this.
Another method, if you can't "control" that deep you controls, is to mark somewhat the "good controls", that is the ones which should not trigger the away-navigation logic.
That is easily achievable setting a global javascript variable such as
var isGoodLink=false;
window.onbeforeunload = function (e) {
var message = "Whatever";
e = e || window.event;
if (!isGoodLink) {
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
}
};
function setGoodLink() {
isGoodLink=true;
}
And add the setGoodLink function on the events you want to keep safe:
<button type="button" onclick="javascript:setGoodLink() ">I am a good button!</button>