After a long day of trying to find a solution to this problem, I keep getting the same issue.
Basically, I have a site, if the user clicks on the "browser-refresh" button, I want to pop-up a "are you sure" alert box with the options "reload" and "don't reload" (Basically, what the browser returns).
Surprisingly, it works just fine in IE. But in chrome or firefox, the refresh happens normally without a popup.
The popup only appears if I click on the body some where and then click on the "browser-refresh" button.
I already the following and other many similar alternatives :
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Any string';
}
// For Safari
return 'Any string';
};
I tried to simulate a click event on page load with 'trigger('click')', '.click()' events.
But, still doesn't work until I click on the body myself (physically).
I've created a short pen, which replicates the issue I'm facing.
https://codepen.io/kanchanrai/pen/LQEZYV
Any help would be very highly appreciated. Thanks in Advance.
Maybe a late answer...
Here is what MDN documentation on beforeunload event states:
Note: To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.
This matches the behavior you observed.
Related
As title, I have this piece of code in my AngularJS project:
window.onbeforeunload = function (e) {
e.preventDefault();
if ($sessionStorage.toReload) {
return 'Are you sure?';
}
};
It works correctly if developer tool window is open, but it doesn't during normal execution. It happens both in Chrome and Firefox.
How can I fix it?
Ok, so the documentation page has the answer:
Note also, that various browsers ignore the result of the event and do
not ask the user for confirmation at all. In such cases, the document
will always be unloaded automatically. Firefox has a switch named
dom.disable_beforeunload in about:config to enable this behavior. As
of Chrome 60, the confirmation will be skipped if the user has not
performed a gesture in the frame or page since it was loaded. Pressing
F5 in the page seems to count as user interaction, whereas
mouse-clicking the refresh arrow or pressing F5 with Chrome DevTools
focused does not count as user interaction (as of Chrome 81).
I tried onbeforeunload event but it's not working when leaving the page it's only working when I reload but every thing works fine on edge.
I think Chrome have changed somethings in configuration.
Is there a way to fix that or another method?
onbeforeunload = function(){
return("bye");
}
AND is there a way I can check if user is closing the page or redirecting to another url with out firing on reloading or can I not do that?
Even when using JQuery, a framework with the objective cross browser compatibility, they say:
The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers and contrasted with the similar beforeunload event.
Source
So you have to accept an inconsistent behaviour.
You could try doing this:
window.onbeforeunload = function(e) {
return "Bye";
}
As you need to attach the event to the window
I'm trying to stop the user from going back in my web app. For this I tried catching the window.onpopstate and added e.preventDefault to cancel the back button effect.
But it doesn't seems to happen.
window.addEventListener('popstate',function(e){
console.log(e); e.preventDefault();
});
Is it not possible to prevent the popstate event of browser? Or am I doing something wrong?
According to this documentation, the popstate event is not cancellable:
Specification: HTML5 Interface: PopStateEvent Bubbles:
Yes
Cancelable: No Target: defaultView Default Action: None
First off "not possible" is never an acceptable answer.
Secondly you can compensate for popstate bugs. In example my rich editor has to constantly compensate for the lazy-bastard key: Backspace. It's not a valid key for a back button (just like spacebar for "page downing") but people impose their personal preferences upon the world instead of adding a browser extension so when people press it sometimes the popstate is triggered instead of the editor removing whatever character is to the left of the keyboard caret.
The following code (dependencies in my platform's documentation) detects when the popstate bug is triggered, slaps it in the face with a e.preventDefault(); and then fixes the address bar address with history.go(1);. The person using the editor doesn't notice anything happened as the browser was not allowed to manipulate the DOM. This code is minimal (other people may be compensating for this bug in various contexts) and I've only tested this in Gecko/Firefox currently so be sure to test Blink, Presto, Trident and WebKit based browsers as well.
window.onpopstate = function(e)
{
if (id_('editor') && is_node_parent(document.activeElement,id_('editor')))
{
e.preventDefault();
history.go(1);
}
}
Long story is short - I am trying to submit a certain form when user closes the window, or is not responding for 20min.
The second I've done using this code:
timeOut = setTimeout(function () {
submitThisForm(document.forms.sendDealerInfo);
console.log("Timed out...");
}, 600000);
For the first one I've tried with this code:
window.onbeforeunload = function() {
submitThisForm(document.forms.sendDealerInfo);
clearTimeout(timeOut);
return null;
}
Unfortunately window.onbeforeunload event won't trigger in all browsers (in Chrome and Opera for example).
I also tried: $(window).unload(function () {... and window.addEventListener("beforeunload", function (event) {...
But same story - they won't work in all browsers.
Is there a way to accomplish what I am trying to do some other way? Perhaps with sessions?
As Suman says, onBeforeUnload is supported in all the major browsers. But most, if not all, the browsers will not let you do anything within that event beyond returning a string for the "Are you sure you want to leave this page?" dialog.
Then with onUnload you're attempting to submit a form after the page has already been unloaded, and navigation is already happening. It would be a very odd user experience to be navigating away then be redirected somewhere else.
Trying to submit a form when the window is closed isn't a very safe method. The web browser could crash, the user could force close it, the internet connection could be interrupted, among other things. I think your best bet would be to submit the form every so often. Possibly detecting an idle timeout of a few seconds, then submitting your form?
window.onbeforeunload is works in all major browsers, Like it is supported from Chrome 1 and Opera 12
Browser Compability
I'm working on a web app and I have a situation where I want to allow the user to press a keyboard shortcut to open something in a new tab or window. Obviously popup blockers can create problems here. I know they try to be intelligent by determining if the popup window was initiated from some sort of user interaction (click, keypress, etc...). Chrome seems to handle this fine, opening the new tab when pressing the keyboard shortcut, but Firefox blocks it.
I've tried a number of things, including pretty much all the solutions presented in this SO question, but nothing seems to work for FF. It works fine in FF if the function that pops up the new window is called from a click event handler, but not from a keyboard event handler. Question is, does anybody know of a way to make this work from a keyboard event in FF?
Here was my latest attempt to make it work (works with Chrome but not FF):
var $newTabEl = $('<div>');
$(document.body).append($newTabEl);
$newTabEl.click(function() {
$(this).target = "_blank";
window.open('/request/preview/requestId/' + data.get('id'));
return false;
});
$newTabEl.click();
$newTabEl.remove();