Show alert when the user click the browser back button - javascript

Iv been trying to figure out the best way to do this without much luck. I would like to do something if the user clicks back such as showing a custom dialog.
I have tried this which works to a certain extend:
var url = 'www.examples.com';
history.pushState(
{
pushStateUrl: url
},
url,
url
);
window.onpopstate = function() {
showDialog();
};
But it doesnt feel clean as it involves manipulating the browser history. Is there any better way to detect back without changing the history.
p.s. it does not have to work in all browsers. And preferably not using jquery.
Also beforeunload does not work in my case as I cannot show my own custom dialog.

this is a late response but I am posting in the intention of this could help to someone like me
add **beforeunload** event lister for your page when loaded
and remove it when submitting the form or whenever you want
step 1: var stayOnPage =function(){
confirm("Would you like to save this draft?");
if (!stayOnPage) {
history.back() or
// do your stuff
} else {
// do your stuff
}
}
window.addEventListener('beforeunload',stayOnPage);
step 2: remove event listener when you want
function onSubmitForm(){
window.removeEventListener('beforeunload',stayOnPage);
}
<button onclick="onSubmitForm()"> Submit </button>
if this doesn't work
change beforeunload to popstate
i.e
function onSubmitForm(){
window.addEventListener('popstate', stayOnPage);
}

Try this and it's found here
window.onbeforeunload = onBack;
function onBack(evt)
{
if (evt == undefined)
evt = window.event;
if ( (evt.clientX < 0) ||
(evt.clientY < 0) ||
(evt.clientX > document.body.clientWidth) ||
(evt.clientY > document.body.clientHeight)
)
{
alert('Unload from browser button press');
return "You clicked some browser button? Do you want to move away from this page?";
}
return undefined;
}

Related

Disable browsers' back button, completely

Need to prevent users going to the previous page, completely.
When I use the following code it works but it's not what I need exactly. When pressing the back button it says "Document Expired":
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Another idea - to open a new window without toolbar:
<script>
function PopupWithoutToolbar(link) {
var w = window.open(link.href,
link.target || "_blank",
'menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,dependent,width=800,height=620,left=0,top=0');
return w ? false : true;
}
</script>
yahoo
But, still... If the user presses the backspace button on a keyboard he can go back. It seems that this approach is only for hiding and not disabling buttons.
Is there any way to simply ignore the back button?
I am not entirely sure if this will work, but you can try handling the event with javascript.
Like if you want to entirely disable the backspace button from allowing users to go back you can do like
$(window).on("keypress", function (e){
if(e.keycode == "backspace")
e.preventDefault();
})
I could figure out the keycode for backspace for you , but that isn't too hard to figure out. Also this uses jquery, but you can use just raw javascript. just wasn't sure what it would be offhand.
I'm using a slightly different solution:
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
}
Based on your post it sounds like your only issue is disabling the backspace button from allowing the user to go back.
Here's what I do for that using jquery. Still allows backspace to work inside enabled text editing inputs, where it should.
// Prevent the backspace key from navigating back.
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8) {
var d = event.srcElement || event.target;
if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' ||
d.type.toUpperCase() === 'PASSWORD' ||
d.type.toUpperCase() === 'FILE')) ||
d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
}
else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
}
});
Simplest thing ever:
window.onhashchange = function (event) {
//blah blah blah
event.preventDefault();
return false;
}
You can handle the location domain etc from that (window.location) then cancel the event if you want in this case.
How to Detect Browser Back Button event - Cross Browser
To disable the back button in the browser you can use use the following code in your JavaScript on the page on which you want to disable the back button.
<script>
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
</script>

javascript beforeunload detect refresh versus close

Using the following function is it possible to detect which button the user has
pressed the refresh button or the close button? If not is there another way?
$(window).bind('beforeunload', function(event) {
return 'pls save ur work';
});
The simple answer is no - browsers' security models do not allow you to explicitly detect in what way a user has chosen to leave your page (refresh / close / internal link / external link).
detect refresh browser for unload/beforeunload when browser closed
It is possible - using a cookie - to check when a user loads your page whether they were previously on that site in the same session - e.g. detect if they have refreshed - but not before they refresh:
Detect Browser Refresh in Javascript
Check if page gets reloaded or refreshed in Javascript
A partial and imperfect approach would be to detect whether they pressed "F5" or "Ctrl+R" or "Cmd+R" (keyboard shortcuts for refresh) just before the page unload. This will detect some refreshes, but not where the user actually clicked the refresh button.
(function($) {
var refreshKeyPressed = false;
var modifierPressed = false;
var f5key = 116;
var rkey = 82;
var modkey = [17, 224, 91, 93];
// Check for refresh keys
$(document).bind(
'keydown',
function(evt) {
// Check for refresh
if (evt.which == f5key || window.modifierPressed && evt.which == rkey) {
refreshKeyPressed = true;
}
// Check for modifier
if (modkey.indexOf(evt.which) >= 0) {
modifierPressed = true;
}
}
);
// Check for refresh keys
$(document).bind(
'keyup',
function(evt) {
// Check undo keys
if (evt.which == f5key || evt.which == rkey) {
refreshKeyPressed = false;
}
// Check for modifier
if (modkey.indexOf(evt.which) >= 0) {
modifierPressed = false;
}
}
);
$(window).bind('beforeunload', function(event) {
var message = "not refreshed";
if (refreshKeyPressed) {
message = "refreshed";
}
event.returnValue = message;
return message;
});
}(jQuery));
You can also detect when a link is clicked whether the target of the link is on the same site or not:
How can I detect when the user is leaving my site, not just going to a different page?

Phonegap - Determine exact element active

I need to change the back button functionality of my phonegap project, which I've succeeded in doing without any problem. The only issue now, is that I need to further change the functionality based on if the user has a certain field selected.
Basically, if the user has clicked in a field with the id of "date-selector1", I need to completely disable the back button.
I was attempting to use document.activeElement, but it only returns the type of the element (input in this case), but I still want the functionality to work when they are in a general input, but not when they are in an input of a specific id.
EDIT
I tried all of the suggestions below, and have ended up with the following code, but still no success.
function pluginDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false);
}
function onBackKeyDown() {
var sElement = document.activeElement;
var isBadElement = false;
var eList = ['procedure-date', 'immunization-date', 'lab-test-done', 'condition-onset', 'condition-resolution', 'medication-start-date', 'medication-stop-date', 'reaction-date'];
console.log("[[ACTIVE ELEMENT: --> " + document.activeElement + "]]");
for (var i = 0;i < eList.length - 1;i++) {
if (sElement == $(eList[i])[0]) {
isBadElement = true;
}
}
if (isBadElement) {
console.log('Back button not allowed here');
} else if ($.mobile.activePage.is('#main') || $.mobile.activePage.is('#family') || $.mobile.activePage.is('#login')) {
navigator.app.exitApp();
} else {
navigator.app.backHistory();
}
}
if you're listening for the back button you can add this if statement:
if (document.activeElement == $("#date-selector1")[0]) {
/*disable button here, return false etc...*/
}
or even better (Thanks to Jonathan Sampson)
if (document.activeElement.id === "date-selector1") {
/*disable button here, return false etc...*/
}
You can have a flag set when a user clicks on a field or you can have a click event (or any other type of event) when a user clicks on the field that should disable the back button.
From the documentation it looks like for the specific page that the backbuton is conditional on you can drop back-btn=true removing that back button.
http://jquerymobile.com/test/docs/toolbars/docs-headers.html
If you need complex conditional functionality you can just create your own button in the header or footer, style it using jquery-mobile widgets and implement your own click functionality.

How to determine which control in window.onbeforeunload in javascript caused the event

I have set up in javascript:
var onBeforeUnloadFired = false;
window.onbeforeunload = function (sender, args)
{
if(window.event){
if(!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
window.event.returnValue = 'You will lose any unsaved changes!'; //IE
}
}
else {
return 'You will lose any unsaved changes!'; //FX
}
windows.setTimeout("ResetOnBeforeUnloadFired()", 1000);
}
function ResetOnBeforeUnloadFired() {
//Need this variable to prevent IE firing twice.
onBeforeUnloadFired = false;
}
I'm trying to achieve an edit screen where the user is warned before navigating away. It works fine except I get the pop up for normal post backs of button clicks. I'm hoping to avoid this so I'm figuring if I could determine which button was pressed it would work.
Does anybody know how to determine which button was pressed in the windows.onbeforeunload?
Alternatively anyone know a better approach to what I'm trying to achieve?
Solved this by putting into an update panel all edit items TextBoxes etc.
Now the windows.onbeforeunload only fires for components external to this.
Another method, if you can't "control" that deep you controls, is to mark somewhat the "good controls", that is the ones which should not trigger the away-navigation logic.
That is easily achievable setting a global javascript variable such as
var isGoodLink=false;
window.onbeforeunload = function (e) {
var message = "Whatever";
e = e || window.event;
if (!isGoodLink) {
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
}
};
function setGoodLink() {
isGoodLink=true;
}
And add the setGoodLink function on the events you want to keep safe:
<button type="button" onclick="javascript:setGoodLink() ">I am a good button!</button>

onbeforeunload confirmation screen customization

Is it possible to create a custom confirmation box for the onbeforeunload event in a browser? I tried but then I get 2 confirmation boxes (one from me which is nothing more than return confirm... and then the standard one from the browser).
At the moment my code looks like:
var inputChanged = false;
$(window).load(function() {
window.onbeforeunload = navigateAway;
$(':input').bind('change', function() { inputChanged = true; });
});
function navigateAway(){
if(inputChanged){
return 'Are you sure you want to navigate away?';
}
}
I'm using jQuery for this.
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;
};
Please note: Most browsers put this message after some other text. You do not have complete control of the content of the confirmation dialog.
No, you can't avoid the standard one from the browser. All you can do is inject some custom text into it; if you use the following event handler (registered the prototype lib way):
Event.observe(window, "beforeunload", function(event) {
if (showMyBeforeUnloadConfirmation)
event.returnValue = "foo bar baz";
});
(and showMyBeforeUnloadConfirmation is true) you'll get the browser's standard confirmation with the following text:
Are you sure you want to navigate away from this page?
foo bar baz
Press OK to continue, or Cancel to stay on the current page.
[ OK ] [ Cancel ]
I faced the same problem, I was able to get its own dialog box with my message, but the problems I faced were:
It was giving message on all navigations and I wanted it only for close click.
With my own confirmation message if user selects "Cancel", it still shows the browser's default dialog box.
Following is the solutions code I found, which I wrote on my Master page.
function closeMe(evt) {
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt && evt.clientX >= (window.event.screenX - 150) && evt.clientY >= -150 && evt.clientY <= 0) {
return "Do you want to log out of your current session?";
}
}
window.onbeforeunload = closeMe;

Categories

Resources