Alert on exit the browser and closing the tab - javascript

I tried onbeforeunload as it requires once user-interaction to call, is there any way to call an event without user-interaction as the user exit the browser after it opens the application tab.
Or Any other solution without using onbeforeunload that prevents the user to exit the browser.
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
$(document).ready(function(){
$(".label").click(function(){
alert('label');
window.onbeforeunload = null;
}
);
$(".new_cont").click(function(){
alert('new_cont');
window.onbeforeunload = null;
}
);
})

In both FireFox and Chrome you need at least one interaction with the page.
Since this feature is to avoid losing data which was entered by the user, if no action happened on the page, then the user did not enter any data.
This is because the onbeforeunload is attached to the 's window object, and when you unload the main page, this event won't fire unless you had focus on this iframe.
<script type="text/javascript">
window.onbeforeunload = function () {
return "Did you save your stuff?"
}
For reference https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Related

Onbeforeunload don't prompt confirmation for page reload

I'm adding an event listener for onbeforeunload that prompts a confirmation message when the user tries to leave the page.
Unfortunately, I don't want the confirmation message to appear when the user tries to reload the page.
How do I do this?
Here's what I have so far:
window.onbeforeunload = function() {
return "";
}
It's completely possible1.
You can listen for the keydown event and check whether the user reloaded the page via the shortcut Ctrl + R. If so, you can set a variable (in our case, isReload) to true and set a timeout to set it back to false after, say, 100 milliseconds.
When the onbeforeunload event fires, check whether isReload is true. If it is, return null to allow the browser to close. Otherwise, return "" to prompt a confirmation.
Demo:
var isReload = false;
document.addEventListener('keydown', function(e){
if(e.ctrlKey && e.keyCode == 82){
isReload = true;
setTimeout(function(){isReload = false}, 100);
}
})
window.onbeforeunload = function(){
if(!isReload){
return "";
}else{
return null;
}
}
1 This only works for the shortcut. You can't differentiate between closure/reload if the user manually clicks the reload button

launch confirm dialog if user changes input without saving

I need to implement in JS a warning if a user changes an input field in a form without saving. The expected behavior is that I make a change into the input and if I try to close the window the confirm dialog appears.
However, what actually happens is when I close the window, the window closes and the dialog does not appear.
I'm referencing the following resources:
Warn user before leaving web page with unsaved changes
JavaScript before leaving the page
This is what I have currently:
var formInputChanged = false;
$(function() {
// activate modal is field is edited
$(".account-settings-form input").on("input", function() {
window.formInputChanged = true;
});
$("input[value='Cancel']").click(function() {
window.formInputChanged = false;
});
window.addEventListener('beforeunload', (event) => {
if (window.formInputChanged) {
confirm("You have unsaved changes");
}
});
});
I have that variable set globally so as far a I understand, should be fully accessible and I'm assigning it to the window in the functions.
I can see in the console.log() that formInputChanged is the correct value.
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
This event enables a web page to trigger a confirmation dialog asking
the user if they really want to leave the page. If the user confirms,
the browser navigates to the new page, otherwise it cancels the
navigation.
What does "leave the page" mean? Back button? X out? Is it an event listener issue?
According to the specification, to show the confirmation dialog an
event handler should call preventDefault() on the event.
I have that in place so that doesn't seem to be the issue...
Why doesn't the confirm modal launch?
Here is a full JS Fiddle demo: https://jsfiddle.net/g6wjrcae/
In the conditional you add:
event.returnValue = "";
return "";
So:
window.addEventListener('beforeunload', (event) => {
event.preventDefault();
if (window.formInputChanged) {
event.returnValue = "";
return "";
}
});
Try this in handler for "beforeunload"
window.addEventListener("beforeunload", function (e) {
if(formInputChanged) {
var confirmationMessage = "You have unsaved changes";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
}
});
I believe confirm("You have unsaved changes"); is where your issue is.

window.onbeforeunload event not fired if we do not click on the page

window.onbeforeunload event is not working for the first time, when we
reload the url no alert coming while closing the browser tab.
But it works when we touch any element on the page and close the tab.
$(document).ready(function(){
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
$(function () {
$("a").click(function () {
window.onbeforeunload = null;
});
});
});
Sample Code here : https://jsfiddle.net/oe9L0fdb/
This is expected behavior on certain browsers. As described here:
To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.
Essentially this is to prevent abuse by web pages.

Fire onbeforeunload confirm alert for external sites only

I am using window.onbeforeunload method to show confirm message if user leaves website.
window.onbeforeunload = function(e) {
return textMsg;
};
But I need this to be fired only if user navigates to external web-site or closes window.
So how to cancel this confirm message for all XHR inside same domain and form submit etc?
Try (untested code):
window.onbeforeunload = function(e) {
return textMsg;
};
$('a:not([href^="http"])').on('click', function() {
window.onbeforeunload = null; // prevent message
});
$('form').on('submit', function() {
window.onbeforeunload = null; // prevent message
});
This will prevent the event from triggering if links do not start with http (external links) and for <form> submits. Looking for a solution for window closing at the moment.

save user email before leaving page

On the cart page of my website, I have to intercept the user leaving the page and ask them if they want to save their cart via email.
I guess I have to use the event "beforeunload" to intercept the user leaving the page, but then I have two problems:
How to exclude from the "beforeunload" trigger the click on the link to proceed with the payment?
How to prompt a small form where I can ask for his email (to be used somehow later) and then proceed with the unload of the page?
For excluding on the link to proceed with the payment, you can do this :-
window.onbeforeunload = function() {
return "You're leaving the site.";
};
$(document).ready(function() {
$('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
$('form').submit(function() { window.onbeforeunload = null; });
});
The only thing u can do is making a default browser messagebox appears...
window.onbeforeunload = foo;
function foo(e) {
if (!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}

Categories

Resources