How to prevent navigation by browser buttons but not by links? - javascript

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

Related

How to handle browser close event through Java script

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/";
}
});

can't use ctrl + click with preventDefault and return false

I'm loading every pages in AJAX so I'm using return false on my links to load them in ajax.
Problem: if the guys want to open it in a new window he can't, ctrl+click activates the ajax as well, I haven't tried middle button because I don't have a mouse.
I then tried e.preventDefault and it still prevents the dude to open it in another tab.
Any idea how I could circumvent this?
(if you want to try: www.p1x3L.com)
e.preventDefault() will prevent the link from being followed by the browser at all.
What I'd be tempted to do is just check the status of the Ctrl (or cmd on a Mac) when the click occurs, and then handle the action.
You'll need to track the action of the keypresses. Consider the following example, which assigns a boolean value to ctrlPressed:
var ctrlPressed = false;
$(window).on('keydown', function(e) {
if (e.metaKey || e.ctrlKey) ctrlPressed = true;
}).on('keyup', function(e) {
if (e.metaKey || e.ctrlKey) ctrlPressed = false;
});
Now inside your click handler, you can just check the status of ctrlPressed:
$('a').on('click', function(e) {
if(ctrlPressed)
{
return true;
}
// Handle your AJAX here. No need for an else{} block
// since return true will already have executed.
});

Execute Javascript function before browser reloads/closes browser/exits page?

Is there a way to execute a function before a user chooses to reload/close browser/exit page?
I need this for an "online/offline" status function i am trying to write. I want to detect whether the user is still on the page or not.
Any ideas? :)
Maybe there is a better approach to this?
Inline function:
window.onbeforeunload = function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
};
or via an event listener (recommended):
window.addEventListener("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
or if you have jQuery:
$(window).on("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
Notes:
When this event returns a non-void value, the user is prompted to
confirm the page unload. In most browsers, the return value of the
event is displayed in this dialog.
Since 25 May 2011, the HTML5 specification states that calls to
window.showModalDialog(), window.alert(), window.confirm() and
window.prompt() methods may be ignored during this event.
See documentation at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
Use window.onbeforeunload, it is triggered when user leaves your page :http://geekswithblogs.net/hmloo/archive/2012/02/15/use-window.onbeforeunload-event-to-stop-browser-from-closing-or-disable.aspx
Try this:
$( window ).unload(function() {
alert( "Handler for .unload() called." );
});
OR this if you want conformation alert
<script>
window.onbeforeunload = function(e) {
return 'Your dialog message';
};
</script>

onbeforeunload keeps poping up an alert box when user click something

I am created a page that warns the user when they click on the (close x) button on the window. I did some reading and discovered that JavaScript had a function called onbeforeonload which can take of the job I was trying to achieve. I however found at after my implementation that, when a user clicks on anything in my window (example: save and enter) The dialog box reappears. I was wondering how I could only target the specific X button in the window.
window.onbeforeunload = function (evt) {
var message = 'Do you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
Right now the function is being called globally... this resource might help you achieve what you are looking for: http://randomdrake.com/2009/09/23/how-to-use-onbeforeunload-with-form-submit-buttons/
This is a "working as intended" behavior for IE. Anchor tag clicks, regardless of whether they navigate or not, will trigger the onbeforeunload event.
This is the workaround I used - I am not sure whether it is the best approach or not:
document.onmouseup = function () {
if (window.event.srcElement.tagName === 'A') {
// turn off your onbeforeunload handler
...
// some small time later, turn it back on
setTimeout(..., 200);
}
};

I want to call function on window unload

I am trying to display confirmation box using window.confirm on window unload event.
If a user clicks on the OK button on confirmation box then I want to call one function and if user clicks the CANCEL button then window should be get closed.
My code is:
<script>
function confirmit(){
var result=window.confirm("Are you sure?");
if(result) {
// close all child windows
} else{
// window should not get close
}
}
</script>
<body onunload='confirmit();' >
But the problem is if I click on CANCEL button, window is getting closed.
Please help me.
You can't prevent unload to stop the page from unloading. You need to bind to onbeforeunload instead. You should just return the string you want to display to the user from the event handler (note that in some browsers the string may not be displayed)
<script type="text/javascript">
window.onbeforeunload = function(e){
var msg = 'Are you sure?';
e = e || window.event;
if(e)
e.returnValue = msg;
return msg;
}
</script>
More info here
JSFiddle Example here
change your code to this to make it work cross-browser:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Do you really want to exit?';
}
// For Safari
return 'Do you really want to exit?';
};
</script>
<body>
...
note that this is using the onbeforeunload-event (more information / view an example) where the return-value has to be the message that should be shown to the user.
i don't know if you'll have a chance to react on the confirmation to do something after that (closing child-windows for example), but i don't think so.

Categories