I need to execute some code before leaving the browser, I implemented this:
window.onbeforeunload = function () { return 'Are you sure?'; };
window.onunload = function () { releaseLocking(); };
It works pretty well with Google Chrome. When closing GC: a message is shown,
if I click on the button 'stay on the page', nothing will happen. Perfect.
if I click on the button 'leave the page', the code under releaseLocking will be executed. Perfect.
I have problems with Internet Explorer.
if I click on the button 'stay on the page', nothing will happen. Perfect.
if I click on the button 'leave the page', the code under releaseLocking won't get executed.
Any idea?
I searched a lot but didnt found a solution.
Thanks.
UPDATE
var releaseLocking = function() {
// Release only if lock is set on the current user
if (transport().lockedById() == 5) { // 5 is dummy (Jean Dupont for testing)
transport().lockedById(null);
transport().lockedTime(null);
return ctxTransport.saveChanges(SILENTSAVE);
}
};
It's seems IE have bug where the unload event wouldn't fire on a specific page on a site.
the unload event never fired since all the contents of the page hadn't finished loading before it's navigated to another page.
try stopping it before you unload
try this:
function fixUnload() {
// Is there things still loading, then fake the unload event
if (document.readyState == 'interactive') {
function stop() {
// Prevent memory leak
document.detachEvent('onstop', stop);
// Call unload handler
unload();
};
// Fire unload when the currently loading page is stopped
document.attachEvent('onstop', stop);
// Remove onstop listener after a while to prevent the unload function
// to execute if the user presses cancel in an onbeforeunload
// confirm dialog and then presses the stop button in the browser
window.setTimeout(function() {
document.detachEvent('onstop', stop);
}, 0);
}
};
function unload() {
alert('Unload event occured.');
};
window.attachEvent('onunload', unload);
window.attachEvent('onbeforeunload', fixUnload);
These types of events are very unreliable.. what if the user's browser crashes (lol ie!) I was able to achieve the same outcome by using a heartbeat and polling the server every 20-30 seconds (or longer idk what your duration may be) and using that to handle the exiting event.. I had a locking mechanism in this app too.
Good luck.
Related
Is it possible with jquery to trigger a function when the user clicks the browsers back button.
I have a lightbox/widget that when open fills the window when it is open. There is a close button etc but this would be good if this closed if a user hit the back button by mistake.
I have this so far but the function doesnt seem to run at all
$(window).on("navigate", function (event, data) {
event.preventDefault();
console.log('BACK PRESSED');
var direction = data.state.direction;
if (direction === 'back') {
if(widgets.full_active){
$('.close', widgets.active_widget).click();
event.preventDefault();
console.log('CLOSE THIS');
}
}
if (direction === 'forward') {
// do something else
}
});
By not running this line at the start of the function event.preventDefault(); should mean the page never changes
Usually, I do this using the native JavaScript API from the browser, like described here: Manipulating the Broser History.
With jQuery, I see people usually using this plugin: History.js, although I have no idea what is it's status.
The event you're looking for is onpopstate.
A popstate event is dispatched to the window every time the active
history entry changes between two history entries for the same
document.
I'm trying to reliably identify when a browser window/tab is activated and deactivated. Normally, window's focus and blur events would do, but the document contains several iframes.
When an iframe is focused, the main window gets unfocused and vice versa, so we have the following possibilities of focus events [(none) means the window/tab is deactivated]:
current focus new focus events
----------------------------------------------------------------------
window (none) window:blur
window iframe window:blur + iframe:focus
iframe (none) iframe:blur
iframe window iframe:blur + window:focus
iframe another iframe iframe:blur + iframe:focus
(none) window window:focus
(none) iframe iframe:focus
It is no problem to register all of these events, as shown by this fiddle. But whenever we switch from the main window to an iframe or vice versa, or between two iframes, the respective blur and focus events both fire; and they fire with a small delay at that.
I am worried about the concurrency here, since the blur handler could go and start doing stuff, but it should have never started because the user actually just switched focus somewhere in between the frames.
Example: A page should do some AJAX requests periodically whenever it is currently not active. That is, it should start requesting whenever the user deactivates the tab and stop requesting as soon as it's activated again. So we bind a function to the blur event that initiates the requests. If the user just clicks on another iframe, blur, and shortly after that, focus is triggered. But the blur handler already fires away, making at least one request before it can be stopped again.
And that's my problem: How can I reliably detect when a user actually (de-)activates a browser window containing iframes, without risking to get a false alarm caused by two immediate blur and focus events?
I wrote a half-baked solution that uses a timeout after a blur event in order to determine if there was an immediate focus event after it (fiddle):
var active = false,
timeout = 50, // ms
lastBlur = 0,
lastFocus = 0;
function handleBlur() {
if (lastBlur - lastFocus > timeout) {
active = false;
}
}
function handleFocus() {
if (lastFocus - lastBlur > timeout) {
active = true;
}
}
$(window).on('focus', function () {
lastFocus = Date.now();
handleFocus();
}).on('blur', function () {
lastBlur = Date.now();
window.setTimeout(handleBlur, timeout);
});
$('iframe').each(function () {
$(this.contentWindow).on('focus', function () {
lastFocus = Date.now();
handleFocus();
}).on('blur', function () {
lastBlur = Date.now();
window.setTimeout(handleBlur, timeout);
});
});
But I believe this could be very problematic, especially on slower machines. Increasing the timeout is also not acceptable to me, 50 ms is really my pain threshold.
Is there a way that doesn't depend on the client to be fast enough?
you could poll for the document.hasFocus() value, which should be true if either an iframe or the main window are focused
setInterval(function checkFocus(){
if( checkFocus.prev == document.hasFocus() ) return;
if(document.hasFocus()) onFocus();
else onBlur();
checkFocus.prev = document.hasFocus();
},100);
function onFocus(){ console.log('browser window activated') }
function onBlur(){ console.log('browser window deactivated') }
I was trying to do it without polling, but the iframe doesn't fire an onblur event (if the browser window is deactivated when the iframe was on focus, I get no events fired), so I ended up needing polling for half of it anyway, but maybe someone can figure something out with this code
function onFocus(){ console.log('browser window activated'); }
function onBlur(){ console.log('browser window deactivated'); }
var inter;
var iframeFocused;
window.focus(); // I needed this for events to fire afterwards initially
addEventListener('focus', function(e){
console.log('global window focused');
if(iframeFocused){
console.log('iframe lost focus');
iframeFocused = false;
clearInterval(inter);
}
else onFocus();
});
addEventListener('blur', function(e){
console.log('global window lost focus');
if(document.hasFocus()){
console.log('iframe focused');
iframeFocused = true;
inter = setInterval(()=>{
if(!document.hasFocus()){
console.log('iframe lost focus');
iframeFocused = false;
onBlur();
clearInterval(inter);
}
},100);
}
else onBlur();
});
I'm trying to implement a warning for the users in case they are leaving the form without saving.
The warning dialog works as expected but with the only exception that when the user chooses to 'Stay on Page', the selected side menu entry changed to the one the user clicked on (form is the same).
How can I make sure that the same menu item is still selected once the user chooses to 'Stay on Page'?
var warnMessage = "Unsaved changes. Do you really want to leave the page?";
$(document).ready(function () {
$('a.k-link').on('click', function () {
window.onbeforeunload = function () {
if (isDirty) return warnMessage;
}
});
});
You might find it easier (and possibly more consistent across browsers) to use a confirm prompt (remember, it's a blocking dialog).
<script>
var warnMessage = "Unsaved changes. Do you really want to leave the page?";
$('a.k-link').on('click', function (e) {
if (isDirty && !confirm(warnMessage)) {
e.preventDefault();
}
});
</script>
There are at least two reasons to avoid onbeforeunload:
The spec doesn't require a browser to display the message you
provide, and not all browsers do, and
the correct event is actually beforeunload
You can and should handle this event through window.addEventListener() and the beforeunload event. More documentation is available there. (MDN)
I'm just guessing, since the Kendo UI scripts aren't exactly fun to read through, but the 'selected' class is getting applied because a navigation event was started, even though you cancel it; the Kendo script is probably just listening for a successful click. onbeforeunload and beforeunload both happen after the click event has resolved (AFAIK, anyway).
Following worked for me (adding e.stopPropagation):
$('a.k-link').on('click', function (e) {
if (isDirty && !confirm(warnMessage)) {
e.preventDefault();
e.stopPropagation();
} });
or by returning false:
$('a.k-link').on('click', function (e) {
if (isDirty && !confirm(warnMessage)) {
return false;
} });
Is there a way to capture to result of the window.onbeforeunload confirmation dialog like the one below from Stack Overflow (this happens when leaving the 'Ask Question' page without posting the question)?
This is how it appears in Chrome, I believe it's slightly different in other browsers, but you always have some form of yes/no buttons.
Presumably if they're still on the offending page after the event has been triggered they chose to stay and you could probably figure this out by watching the sequence of js. However I would like to know how to determine if they clicked "Leave this page"?
I've implemented this like below:
// concept taken from SO implementation
function setConfirmUnload(showMessage, message) {
window.onbeforeunload = showMessage ? (message ? message : "this is a default message") : null;
}
// pseudo code
listen to changes on inputs
if any inputs fire a change event
call setConfirmUnload(true, 'My warning message')
note I'm using jQuery within my site.
I'm essentially trying to implement a Gmail like drafting implementation, wherein if a user leaves a page with a form they've made changes to without saving they're warmed with a similar dialog. If they choose to discard they're changes and leave the page, I need to clean up some temporary records from the database (I'm thinking an AJAX call, or simply submitting the form with a delete flag) then sending them on their way.
My question also relates to:
jQuery AJAX call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?
You can have the exit confirmation using window.onbeforeunload but there isn't a way to find out which button the user clicked on.
To quote an earlier response from jvenema from this thread:
The primary purpose for the
beforeunload is for things like
allowing the users the option to save
changes before their changes are lost.
Besides, if your users are leaving,
it's already too late [...]
How about this:
$( window ).bind( 'beforeunload' , function( event ) {
setTimeout( function() {
alert( 'Hi againe!' );
} );
return '';
} ).bind( 'unload', function( event ) {
alert( 'Goodby!' );
} );
Late to the party, but I found the following code (in TypeScript) to be a decent way to detect if the person clicked on 'Ok' on that confirmation dialogue window.
public listenToUnloadEvents(): void {
window.addEventListener('beforeunload', (e) => {
const confirmationMessage = '\o/';
(e || window.event).returnValue = confirmationMessage; // Gecko + IE
return confirmationMessage; // Webkit, Safari, Chrome etc.
});
window.addEventListener('unload', () => {
this.sendNotification(Action.LEFT)
});
}
I'm not sure how much time you have to run code in the unload event, but in this instance, I am sending a notification through Socket.io, so it's very quick at completing.
As for detecting the cancel on that notification, as someone else mentioned, creating a global variable like let didEnterBeforeUnload = false could be set to true when the beforeunload event fires. After this, by creating the third event, like so (again, in TypeScript), you can infer the user pressing cancel
window.addEventListener('focus', (e) => {
if (didEnterBeforeUnload) {
console.log('pressed cancel')
}
didEnterBeforeUnload = false
});
As a side-note though, these events won't (iirc) fire unless you have interacted with the page. So make sure to click or tap into the page before trying to navigate away during your testing.
I hope this helps anyone else out there!
I am popping up a dialog box when someone tries to navigate away from a particular page without having saved their work. I use Javascript's onbeforeunload event, works great.
Now I want to run some Javascript code when the user clicks "Cancel" on the dialog that comes up (saying they don't want to navigate away from the page).
Is this possible? I'm using jQuery as well, so is there maybe an event like beforeunloadcancel I can bind to?
UPDATE: The idea is to actually save and direct users to a different webpage if they chose cancel
You can do it like this:
$(function() {
$(window).bind('beforeunload', function() {
setTimeout(function() {
setTimeout(function() {
$(document.body).css('background-color', 'red');
}, 1000);
},1);
return 'are you sure';
});
});
The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling the return statement, which in turn triggers the browsers modal dialog. This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed. If the user pressed cancel, it will trigger another setTimeout which fires in about one second. If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.
example: http://www.jsfiddle.net/NdyGJ/2/
I know this question is old now, but in case anyone is still having issues with this, I have found a solution that seems to work for me,
Basically the unload event is fired after the beforeunload event. We can use this to cancel a timeout created in the beforeunload event, modifying jAndy's answer:
$(function() {
var beforeUnloadTimeout = 0 ;
$(window).bind('beforeunload', function() {
console.log('beforeunload');
beforeUnloadTimeout = setTimeout(function() {
console.log('settimeout function');
$(document.body).css('background-color', 'red');
},500);
return 'are you sure';
});
$(window).bind('unload', function() {
console.log('unload');
if(typeof beforeUnloadTimeout !=='undefined' && beforeUnloadTimeout != 0)
clearTimeout(beforeUnloadTimeout);
});
});
EDIT: jsfiddle here
Not possible. Maybe someone will prove me wrong... What code do you want to run? Do you want to auto-save when they click cancel? That sounds counter-intuitive. If you don't already auto-save, I think it makes little sense to auto-save when they hit "Cancel". Maybe you could highlight the save button in your onbeforeunload handler so the user sees what they need to do before navigating away.
I didn't think it was possible, but just tried this idea and it works (although it is some what of a hack and may not work the same in all browsers):
window.onbeforeunload = function () {
$('body').mousemove(checkunload);
return "Sure thing";
};
function checkunload() {
$('body').unbind("mousemove");
//ADD CODE TO RUN IF CANCEL WAS CLICKED
}
Another variation
The first setTimeout waits for the user to respond to the browser's Leave/Cancel popup. The second setTimeout waits 1 second, and then CancelSelected is only called if the user cancels. Otherwise the page is unloaded and the setTimeout is lost.
window.onbeforeunload = function(e) {
e.returnValue = "message to user";
setTimeout(function () { setTimeout(CancelSelected, 1000); }, 100);
}
function CancelSelected() {
alert("User selected stay/cancel");
}
window.onbeforeunload = function() {
if (confirm('Do you want to navigate away from this page?')) {
alert('Saving work...(OK clicked)')
} else {
alert('Saving work...(canceled clicked)')
return false
}
}
with this code also if user clicks on 'Cancel' in IE8 the default navigation dialog will appear.