Hello I want to call API when user close browser so I have use bellow function
window.onbeforeunload = function (event) {
var message = 'Sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
so this function showing me two buttons "Leave" and "stay"
I want to call API if user click on leave button , but I am not getting any event because it directly close when I click on leave so anyone have any suggestion how can I do this.
Related
How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser using Javascript and not using Jquery Mobile library.
Solution would be really appreciated. I tried with few solutions online, but nothing seemed to work.
You should never do that. https://www.irt.org/script/311.htm
By the way, you may just warn the user using window.onbeforeunload.
You can-not actually disable browser back button. And there is no event for capturing the back button click.
If it is really necessary you can do something like that:
(function (global) {
var _extra_hash = "!";
var noBack = function () {
global.location.href += "#";
global.setTimeout(function () {
global.location.href += _extra_hash;
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _extra_hash) {
global.location.hash = _extra_hash;
}
};
global.onload = function () {
noBack();
// this is for disabling backspace on page except on input fields and textarea..
/*document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
};*/
}
})(window);
But the user can still kill the tab. Anyway, It is generally a bad idea overriding the default behavior of web browser.
I tried to disable onbeforeunload event from frame script with this command:
window.parent.onbeforeunload = null;
but received this dialog:
I tried to debug and onbeforeunload becomes null. But how I can do so this dialog not shown?
For additional information, I need to trigger this event with JS. At start of the page I set:
window.parent.onbeforeunload = confirm;
where confirm is my own function. But in some places of code I need to disable this event and after that enable with the same command.
This could be happening because null is basically an object in Javascript. Here is how I had written it:
var confirmCloseFn = function(evt) {
if (!captureClose) return;
var message = getLogoffMsg();
evt = (evt) ? evt : window.event;
if(message) {
if (evt) evt.returnValue = message;
return message;
}
else {
if (evt) evt.returnValue = null;
return null;
}
};
How can i redirect him if a user clicks on leave a page button on onbeforeunload. Please check my code
function openNewWindow() {
window.open('http://google.com/','_blank');
window.focus();
}
window.onbeforeunload = function(event) {
event = event || window.event;
var confirmClose = 'Are you sure?';
if (event) {
event.returnValue = confirmClose;
if(confirmClose)
{
if(true)
{
openNewWindow();
}
}
return confirmClose;
}
}
Thanks
If the users chooses yes in the onbeforeunload dialog then he will leave the page, you can not prevent this. You can however do some things before the dialog shows, like you are doing in your code, but the dialog it self is only displayed AFTER your function executes, displaying the return value.
Your code seems a bit obscure to, what are you expecting from if(confirmClose), this will always evaluate to true because a non empty string is "truthy" in javascript.
I have implemented an "unsaved changes" warning using techniques described on these pages:
Client/JS Framework for "Unsaved Data" Protection?
http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
This works well except for a DropDownList on the page. It does an AutoPostBack, and I want onbeforeunload to fire because unsaved changes will be lost, but it isn't working. Should it be raising the onbeforeunload event? Can I somehow make it raise the event?
Edit:
The DropDownList is inside an UpdatePanel, so that means it isn't unloading the page and that would be why onbeforeunload isn't being triggered. Is there any way I can trigger the event programmatically? Or do I have to roll my own imitation Confirm dialog?
Edit2
I now have a solution that adds the dialog to asynchronous postbacks from an UpdatePanel. I have edited the original script, adding the call to setConfirmAsyncPostBack() as described in my solution.
Here is my JavaScript:
/****Scripts to warn user of unsaved changes****/
//https://stackoverflow.com/questions/140460
//http://jonstjohn.com/node/23
//Activates the confirm message onbeforeunload.
function setConfirmUnload(on) {
setConfirmAsyncPostBack();
if (on) {
removeCheckFromNoWarnClasses();
fixIEonBeforeUnload();
window.onbeforeunload = unloadMessage
return;
}
window.onbeforeunload = null
}
function unloadMessage() {
return 'You have unsaved changes.';
}
//Moves javascript from href to onclick to prevent IE raising onbeforeunload unecessarily
//http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
function fixIEonBeforeUnload() {
if (!$.browser.msie)
return;
$('a').filter(function() {
return (/^javascript\:/i).test($(this).attr('href'));
}).each(function() {
var hrefscript = $(this).attr('href');
hrefscript = hrefscript.substr(11);
$(this).data('hrefscript', hrefscript);
}).click(function() {
var hrefscript = $(this).data('hrefscript');
eval(hrefscript);
return false;
}).attr('href', '#');
}
//Removes warnings from Save buttons, links, etc, that have been can be given "no-warn" or "no-warn-validate" css class
//"no-warn-validate" inputs/links will only remove warning after successful validation
//use the no-warn-validate class on buttons/links that cause validation.
//use the no-warn class on controls that have CausesValidation=false (e.g. a "Save as Draft" button).
function removeCheckFromNoWarnClasses() {
$('.no-warn-validate').click(function() {
if (Page_ClientValidate == null || Page_ClientValidate()) {
setConfirmUnload(false);
}
});
$('.no-warn').click(function() {
setConfirmUnload(false);
});
}
//Adds client side events to all input controls to switch on confirmation onbeforeunload
function enableUnsavedChangesWarning() {
$(':input').one('change', function() {
window.onbeforeunload = function() {
return 'You have unsaved changes.';
}
});
removeCheckFromNoWarnClasses();
}
And in my ASP.NET page, when the user makes a change:
if (changed)
{
...
//Confirm unload if there are unsaved changes.
//NB we also have to call fixIEonBeforeUnload() to fix links, done in in page load to include links that are rendered during callbacks
ScriptManager.RegisterStartupScript(Page, GetType(), "unsavedchanges", "setConfirmUnload(true);", true);
}
else
...
Also see How to prevent AutoPostBack when DropDownlist is selected using jQuery
//http://msdn.microsoft.com/en-us/magazine/cc163413.aspx
//https://stackoverflow.com/questions/2424327/prevent-asp-net-dopostback-from-jquery-submit-within-updatepanel
//Adds an event handler to confirm unsaved changes when an asynchronous postback is initialised by an UpdatePanel
function setConfirmAsyncPostBack() {
if (typeof (Sys.WebForms) === "undefined" || typeof (Sys.WebForms.PageRequestManager) === "undefined")
return;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(confirmAsyncPostBack);
}
//An event handler for asynchronous postbacks that confirms unsaved changes, cancelling the postback if they are not confirmed
//Adds the confirmation to elements that have a css class of "warn"
function confirmAsyncPostBack(sender, args) {
if (window.onbeforeunload != null && args.get_postBackElement().className == "warn" && !unloadConfirmed())
args.set_cancel(true);
}
//Displays a confirmation dialog that imitates the dialog displayed by onbeforeunload
function unloadConfirmed() {
var confirmed = confirm("Are you sure you want to navigate away from this page?\n\n" + unloadMessage() + "\n\nPress OK to continue or Cancel to stay on the current page.");
if (confirmed)
window.onbeforeunload = null;
return confirmed;
}
I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}