Anybody know how to detect browsers refresh and back button events in firefox using jquery or javascript.
For back button:
window.addEventListener('popstate', function (event) {
//Your code here
});
For Refresh:
window.onbeforeunload = function () {
// Your code here
}
You can try WindowEventHandlers.onbeforeunload:
window.onbeforeunload = function(e) {
};
and
$(window).unload(function() {
//
});
Also check Browser Back Button Detection:
I have made a very reusable javascript class, that can be simply
dropped into your web page, and when the user clicks back, it will
call a function. The default function on this call is a javascript
alert “Back Button Clicked”.
To replace this functionality, you simply need to override the OnBack
function. This can be done by using the code below.
<script type="text/javascript">
bajb_backdetect.OnBack = function()
{
alert('You clicked it!');
}
</script>
This will now replace the “Back Button Clicked” alert with a “You
clicked it!’” alert.
Check this page: Manipulating the browser history
You can probably get something working with using history.pushState and window.onpopstate
You can use the following events:
window.onpopstate for back button press.
window.onpopstate = (e) => {
// your logic goes here
};
window.onbeforeunload for refresh or tab close.
window.onbeforeunload = (e) => {
// your logic here
e.preventDefault();
e.returnValue = 'There are unsaved changes. Sure you want to leave?';
};
Related
I have an application which logs users session once he logins. Say i have view case page and when user click a case it would be locked by that user and the action is tracked by inserting an entry into lock table with the java Session, caseid and userId. Now when the user click any other tab within the application, including logout an action is called to delete the session id in the lock table for that user and case. I have a requirement to release this lock even when the user closes the browser close button. My backend code will handle the scenario when the elapsedTime of the lock is greater than 10mins. However when the user closes the browser and some other user logins to view the same case within this span of 10mins it still shows the lock by the previous user. So i have to catpure the browser close event and do the same action as i do for logout and other tab click. My below piexe of java script code works well in IE browser for browser close but doesnt work in chrome or firefox. Can someone suggest which event to use in chrome/firefox please?
<script type="text/javascript">
document.getElementById('logoff').onclick = function(){
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
};
$(document).ready(function(){
var validNavigation = false;
// Attach the event keypress to exclude the F5 refresh (includes normal refresh)
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
$("input[type=button]").bind("click", function() {
validNavigation = true;
});
window.onbeforeunload = function() {
if (!validNavigation) {
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
}
};
});
</script>
It seems like using the onbeforeunload property is discouraged:
Typically, it is better to use window.addEventListener() and the beforeunload event, instead of onbeforeunload.
It should look like this:
window.addEventListener('beforeunload', function (e) {
// the absence of a returnValue property on the event will guarantee the browser unload happens
delete e['returnValue'];
if (!validNavigation) {
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
}
});
I want to prevent the user from refreshing the page, How to do this? I have been using e.preventDefault method but it`s not running properly.
you can use the window.onbeforeunload even.
window.onbeforeunload = function() {
return "you can not refresh the page";
}
The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue to prompt the user.
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = '';
});
Reference: WindowEventHandlers.onbeforeunload
Try something like:
<script type="text/javascript">
// Callback
window.onbeforeunload = function(e) {
// Turning off the event
e.preventDefault();
}
</script>
Some basic explanations about these features
preventDefault:
http://www.w3schools.com/jsref/event_preventdefault.asp
beforeunload:
http://www.w3schools.com/jsref/event_onbeforeunload.asp
I want warn users if they leave the page by closing the browser or using the history buttons of the browser using the following javascript:
window.onbeforeunload = function(e) {
return 'Ask user a page leaving question here';
};
But my links and buttons on my website should work regardless of this. How can I achieve that?
The first way that comes to mind is to set a variable that tells you whether a link was clicked:
var linked = false;
window.onbeforeunload = function(e) {
if (!linked)
return 'Ask user a page leaving question here';
};
document.addEventListener('click', function(e) {
if (e.target.tagName === "A")
linked = true;
}, false);
That is, set a click event handler at the document level, that tests whether the clicked element was an anchor (or whatever else you want to allow) and if so sets the variable. (Obviously this assumes that you don't have other anchor element click handlers at a lower level that stop event propagation.)
var linkClicked = false;
window.onbeforeunload = function(e) {
if (!linkClicked){
linkClicked = false;
return 'Ask user a page leaving question here';
}
};
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
});
});
Obviously this relies on JQuery to add the event handler to all links, but you could attach the handler with any other method, including adding onclick="linkClicked=true;" to every link on the page if you really have to.
Edit:
Just want to point out that if the user clicks a link that doesn't redirect them (e.g. a hashtag link to somewhere else on the page, or something that returns false / prevents the default action being executed) then this will set linkClicked to true and subsequently any browser based navigation won't be caught.
If you want to catch this, I would advise setting a timeout on the link click like so:
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
setTimeout(function(){
linkClicked = false;
}, 500);
});
});
This will allow half a second for the window unload event to trigger before resetting the flag so that future navigation events are caught correctly. This still isn't perfect, but it probably doesn't need to be.
You can use the window.onbeforeunload event.
var check= false;
window.onbeforeunload = function () {
if (!check) {
return "Are you sure you want to leave this page?"
}
}
function CheckBackButton() {
check= true;
}
referenceElement.addEventListener('onClick', CheckBackButton(), false);
Us a confirmation prompt no?
like this? Intercept page exit event
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
How to show the “Are you sure you want to navigate away from this page?” when changes committed? this may solve your problem How
I have this little piece of code:
<script>
$(window).bind('beforeunload', function() {
$.ajax({
async: false,
type: 'POST',
url: '/something'
});
});
</script>
I wonder, how could I disable this request when user hits the submit button.
Basically something like here, on SO. When your asking a question and decide to close the page, you get a warning window, but that doesn't happen when you're submitting the form.
Call unbind using the beforeunload event handler:
$('form#someForm').submit(function() {
$(window).unbind('beforeunload');
});
To prevent the form from being submitted, add the following line:
return false;
Use
$('form').submit(function () {
window.onbeforeunload = null;
});
Make sure you have this before you main submit function! (if any)
This is what we use:
On the document ready we call the beforeunload function.
$(document).ready(function(){
$(window).bind("beforeunload", function(){ return(false); });
});
Before any submit or location.reload we unbind the variable.
$(window).unbind('beforeunload');
formXXX.submit();
$(window).unbind("beforeunload");
location.reload(true);
Looking for Detect onbeforeunload for ASP.NET web application well I was,
I've to show warning message if some input control changes on the page using ASP.NET with Master Page and Content Pages. I'm using 3 content placeholders on the master page and the last one is after the form
<form runat="server" id="myForm">
so after the form closing tag and before the body closing tag used this script
<script>
var warnMessage = "Save your unsaved changes before leaving this page!";
$("input").change(function () {
window.onbeforeunload = function () {
return 'You have unsaved changes on this page!';
}
});
$("select").change(function () {
window.onbeforeunload = function () {
return 'You have unsaved changes on this page!';
}
});
$(function () {
$('button[type=submit]').click(function (e) {
window.onbeforeunload = null;
});
});
</script>
beforeunload doesn't work reliably this way, as far as binding goes. You should assign it natively
so I got it working like this bind and unbind didn't work out for me also With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.dirtyforms/2.0.0-beta00006/jquery.dirtyforms.min.js"></script>
<script type="text/javascript">
$(function() {
$('#form_verify').dirtyForms();
})
</script>
<title></title>
<body>
<form id="form_verify" action="a.php" method="POST">
Firt Name <input type="text">
Last Name <input type="file">
<input type="submit">
</form>
if you're using bind then use this:
$('form').submit(function () {
$(window).unbind('beforeunload');
});
This will be good for all form submit.
Super old question but might be useful to others.
Simply detaching the "beforeunload" from the "submit" event would not work for me - because the submit handler was being called even when there were errors in the form that the user had to fix. So if a user attempted to submit the form, then received the errors, then clicked to another page, they would be able to leave without the warning.
Here's my workaround that seems to work pretty well.
(function($) {
var attached = false,
allowed = false;
// catch any input field change events bubbling up from the form
$("form").on("change", function () {
// attach the listener once
if (!attached) {
$("body").on("click", function (e) {
// check that the click came from inside the form
// if it did - set flag to allow leaving the page
// otherwise - hit them with the warning
allowed = $(e.target).parents("form").length != 0;
});
window.addEventListener('beforeunload', function (event) {
// only allow if submit was called
if (!allowed) {
event.preventDefault();
event.returnValue = 'You have unsaved changes.';
}
});
}
attached = true;
});
}(jQuery));
This way, if the click to leave the page originated from inside the form (like the submit button) - it will not display the warning. If the click to leave the page originated from outside of the form, then it will warn the user.
having issues with onbeforeunload. I have a long form broken into segments via a jquery wizard plug in. I need to pop a confirm dialog if you hit back, refresh, close etc on any step but need it to NOT POP the confirm dialog on click of the submit button. had it working, or at least I thought, it doesn't now.
<script type="text/javascript">
var okToSubmit = false;
window.onbeforeunload = function() {
document.getElementById('Register').onclick = function() { okToSubmit = true; };
if(!okToSubmit) return "Using the browsers back button will cause you to lose all form data. Please use the Next and Back buttons on the form";
};
</script>
'Register' is the submit button ID. Please help!
The problem is that the onclick event handler will not be called prior to if(!okToSubmit). All you are doing when you say:
document.getElementById('Register').onclick = function() { okToSubmit = true; };
Is just setting up the event handler. You are not actually retrieving the value of okToSubmit.
One way to fix this might be to setup the onclick event handler before registering onbeforeunload.
Plain old JS syntax a little rusty, so here it is in jQuery if anyone ever needs it, this works, at least for a form submit button. Change method to get if it suits your needs
<script type="text/javascript">
$(document).ready(function(){
var action_is_post = false;
$("form").submit(function () {
action_is_post = true;
});
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (!action_is_post)
return 'Using the browsers back, refresh or close button will cause you to lose all form data. Please use the Next and Back buttons on the form.';
}
});
</script>