Provide custom message when user leaves window without saving data - javascript

Can anybody provide me an custom alert box saying "you are about to leave page and changes will be discarded" Yes/no.
I tried with following code but its giving me default message saying "Changes you made may not be saved"
here is my javascript code
unsaved=true;
window.onbeforeunload = function() {
if (unsaved)
{
var _message = "You currently have unsaved changes!!!\n\nAre you sure you want to exit without saving.\n\nChoose ‘Leave this page’ to exit without saving changes.\nChoose ‘Stay on this page’ to return to the billing profile.";
return _message;
}
}
Also I have no form but simple button which I can't include in form, on click of that button also it giving me warning. Here is Fiddle to try, any help really appreciated thank you. I know there are questions asked on this topic earlier but believe me none are working now.
update there are some methods explained in previous StackOverflow examples but they dont work now in modern browsers.

There's a method in JavaScript called window.confirm(): https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
if (window.confirm("Question"))
console.log('clicked OK');
else
console.log('clicked cancel');

Try this Jquery
$(window).bind('beforeunload', function(){
return 'Your message here';
});
Javascript
window.onbeforeunload = function(){
return 'Your message here';
};

Related

How do I ask the user to confirm they want to leave the page?

I have a web site that contains several pages where the user can add and edit information. In order to provide a consistent UI, I have the following JavaScript function...
function setWindowBeforeUnload(changed) {
$(window).on("beforeunload", function() {
if (confirmLeave && changed && changed()) {
return "You haven't saved the information. If you leave this page, the information will be lost.";
}
});
}
confirmLeave is a global variable that specifies if we are to ask them for confirmation before navigating away (which we don't if we are navigating to another page after a successful save). changed is a function that checks if the entity has changed.
This is called from a details page (say the customer page) as follows...
$(document).ready(function() {
setWindowBeforeUnload(customerChanged);
});
function customerChanged() {
// Checks the data and returns true or false as appropriate
}
This all worked fine until recently, when a change in Chrome broke it.
I have searched for hours, and found loads of people suggesting code like this...
addEventListener('beforeunload', function(event) {
event.returnValue = 'You have unsaved changes.';
});
...which works fine as it is, except that it fires the warning whenever they leave the page, irrespective of whether or not the data has changed.
As soon as I try to add any logic (such as my checking code in the first sample), it doesn't work...
function setWindowBeforeUnload(changed) {
addEventListener('beforeunload', function(event) {
if (confirmLeave && changed && changed()) {
event.returnValue = 'You have unsaved changes.';
}
});
}
With this code, I can navigate away from the page without getting a warning.
Is there any way to reproduce my original behaviour now?
You can use logic in the handler, you just can't have a custom message any more.
See the code below. Use the "Run code snippet" to simulate navigation. Run the snippet, run it again no confirm. Toggle the button to "false" run the snippet and get a confirm.
var test = true;
function otherTest() {
return true;
}
addEventListener('beforeunload', function(event) {
if(!test || !otherTest()) {
event.returnValue = 'You have unsaved changes.';
}
});
document.getElementById('theButton').addEventListener('click', function(event) {
test = !test;
this.innerHTML = test.toString();
});
<p>Click the button to turn the confirm on and off</p>
<button id="theButton">true</button>

How to call JavaScript function in VBA?

I need to by pass an IE confirm 'OK'/'Cancel' pop-up message. I have a problem running a JavaScript function in my VBA script. My JavaScript:
function ConfirmSave()
{
var Ok = confirm('Are you sure all Documents and Information are attached and correct before saving?');
if(Ok)
return true;
else
return false;
}
function submitbutton_click() {
document.getElementById('FileAttachement2_hdnButtonFlag').value = "SAVE";
var submitbutton = document.getElementById('cmdDownSave');
var uploadobj=document.getElementById('FileAttachement2_Uploader1');
if(!window.filesuploaded)
{
if (!ConfirmSave()) return false;
if(uploadobj.getqueuecount()>0)
{
uploadobj.startupload();
}
else
{
//var uploadedcount=parseInt(submitbutton.getAttribute("itemcount"))||0;
//if(uploadedcount>0)
//{
return true;
//}
//alert("Please browse files for upload");
}
return false;
}
window.filesuploaded=false;
return true;
}
In manual process, when I click the save button, the page will pop-up a confirm message box, and my macro will stop running when the pop-up appears unless it has been clicked.
Here is the code I have tried, to click the save button,
Set ElementNameV = HTMLDoc.getElementsByName("cmdsave")
ElementNameV(0).click
I also tried using removeattribute and setattribute with which the pop-up message disappeared but it doesn't upload the file because I need to press the 'OK' in confirm message box that will appear upon clicking the save button to start the file uploading.
ElementNameV(0).removeAttribute ("onclick")
ElementNameV(0).setAttribute "onclick", "return true"
ElementNameV(0).click
I tried running the JavaScript function using below script but it also shows the confirm pop-up message box:
Call HTMLDoc.parentWindow.execScript("submitbutton_click()")
You should be able to overwrite the ConfirmSave function with one which simply returns true:
HTMLDoc.parentWindow.execScript "window.ConfirmSave = function(){return true;};"
or
HTMLDoc.parentWindow.execScript "window.confirm = function(){return true;};"
or even
HTMLDoc.parentWindow.eval "window.confirm = function(){return true;};"
Run that before clicking the button.
Tested and works in IE11
So I've read your question a few times now and I think that to achieve what you want to do you are going to have to completely change your approach to the problem. You need to read up on Javascript Concurency, Javascript Web Workers, and the Javascript Event Loop.
Just throw these terms into Google and you'll find lots of great resources to learn about this.
By default Javascript is a single threaded language and it halts while waiting for events to complete their activities. What you seem to be looking for based on how I'm reading your question is a way for your Javascript to keep performing actions while a user prompt is being displayed.
While this is not an endorsement, I will throw out this one link to get you started.

How to build the jquery/javascript to accomplish event/alert like SO's "Confirm Navigation?" [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to show the “Are you sure you want to navigate away from this page?” when changes committed?
Stackoverflow has a really interesting feature: if you start writing a new question, then you try to navigate away from the page, it will show an alert asking you confirm that you want to leave this page. This works whether you are typing a new address and entering it in the address bar, using the forward/back button, etc..
How does this work? I'd be interested to know less about the alert itself and more specifically about what event/code is triggering the alert.
Thanks!
A flag is set when the textarea is amended. The flag is checked on the unload() event of the window and the alert() is displayed if required. Something like this:
var textAmended = false;
$("textarea").change(function() {
textAmended = true;
});
$(window).unload(function() {
if (textAmended) {
alert('You started writing a question...');
}
});
More information on unload()
This is usually done by checking the value of the textarea, input etc. and changing the window.onunload function, either by passing a string or nothing, like below:
$('textarea').change(function() {
if( this.value == "" ) {
window.onbeforeunload = null;
}else{
window.onbeforeunload = "Are you sure you want to leave?";
}
});
That should trigger the built in confirm!
I think you want some confirmation on just navigating away from current window or closing it:
http://jsfiddle.net/tLWZX/
$(window).on('beforeunload', function() {
return 'You have unsaved changes.';
});
window.onbeforeunload = exit;
function exit() {
var t = 0;
$("textarea").each( function() {
var v = $(this).val();
if(v!="") {
t=t+1;
}
});
if(t>=1) {
return "You Have Some text written in textareas. Still you want to leave?";
}
}
what you wanted is in best and pure way!
http://jsfiddle.net/p4NPh/

JAVASCRIPT: Is that possible to avoid window to close with event beforeunload?

Is that possible to cancel a window close in javascript (via mootools or not) with something like below?
window.addEventListener("beforeunload",function(){doSomething(); return false;})
Yes. You use onbeforeunload and return the string that you want prompted. The browser handles all the work from there for obvious reasons. If the user is okay to leave simply return nothing.
window.onbeforeunload = function()
{
if(...) {
return 'Your changes have NOT been saved.';
}
return;
}
Thank goodness no.
You can however give the user a confirm box just in case they have unsaved changes or some such thing.
window.onbeforeunload = function() {
return 'You have unsaved changes.'
};
Don't annoy your users by trying to keep them on your page. It's only going to backfire, and cause people to actively dislike your site.

Prevent a webpage from navigating away using JavaScript

How to prevent a webpage from navigating away using JavaScript?
Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation:
window.onbeforeunload = function() {
return "";
}
Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.
In older browsers you could specify the message to display in the prompt:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
Unlike other methods presented here, this bit of code will not cause the browser to display a warning asking the user if he wants to leave; instead, it exploits the evented nature of the DOM to redirect back to the current page (and thus cancel navigation) before the browser has a chance to unload it from memory.
Since it works by short-circuiting navigation directly, it cannot be used to prevent the page from being closed; however, it can be used to disable frame-busting.
(function () {
var location = window.document.location;
var preventNavigation = function () {
var originalHashValue = location.hash;
window.setTimeout(function () {
location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
location.hash = originalHashValue;
}, 0);
};
window.addEventListener('beforeunload', preventNavigation, false);
window.addEventListener('unload', preventNavigation, false);
})();
Disclaimer: You should never do this. If a page has frame-busting code on it, please respect the wishes of the author.
The equivalent in a more modern and browser compatible way, using modern addEventListener APIs.
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
I ended up with this slightly different version:
var dirty = false;
window.onbeforeunload = function() {
return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.
With the text in the selected answer you see redundant prompts:
In Ayman's example by returning false you prevent the browser window/tab from closing.
window.onunload = function () {
alert('You are trying to leave.');
return false;
}
The equivalent to the accepted answer in jQuery 1.11:
$(window).on("beforeunload", function () {
return "Please don't leave me!";
});
JSFiddle example
altCognito's answer used the unload event, which happens too late for JavaScript to abort the navigation.
That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.
In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).
A more appropriate error message might be:
window.onbeforeunload = function() {
return "If you leave this page, you will lose any unsaved changes.";
}
Or stackoverflow style: "You have started writing or editing a post."
If you are catching a browser back/forward button and don't want to navigate away, you can use:
window.addEventListener('popstate', function() {
if (window.location.origin !== 'http://example.com') {
// Do something if not your domain
} else if (window.location.href === 'http://example.com/sign-in/step-1') {
window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
} else if (window.location.href === 'http://example.com/sign-in/step-2') {
window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
} else {
// Let it do its thing
}
});
Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.
Use onunload.
For jQuery, I think this works like so:
$(window).unload(function() {
alert("Unloading");
return falseIfYouWantToButBeCareful();
});
If you need to toggle the state back to no notification on exit, use the following line:
window.onbeforeunload = null;

Categories