detect back button click in browser [duplicate] - javascript

This question already has answers here:
Intercepting call to the back button in my AJAX application
(12 answers)
Closed 8 years ago.
I have to detect if a user has clicked back button or not.
For this I am using
window.onbeforeunload = function (e) {
}
It works if a user clicks back button. But this event is also fired if a user click F5
or reload button of browser. How do I fix this?

So as far as AJAX is concerned...
Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.

Please try this (if the browser does not support "onbeforeunload"):
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
}
}
});
window.history.pushState('forward', null, './#forward');
}
});

best way I know
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = "Do you really want to leave this page?"
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};

I'm detecting the back button by this way:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
It works but I have to create a cookie in Chrome to detect that i'm in the page on first time because when i enter in the page without control by cookie, the browser do the back action without click in any back button.
if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null);
window.onpopstate = function () {
if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null )
{
addCookie('cookieChrome',1, 1440);
}
else
{
history.pushState('newjibberish', null, null);
}
};
}
AND VERY IMPORTANT, history.pushState("jibberish", null, null); duplicates the browser history.
Some one knows who can i fix it?

Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:
http://www.irt.org/script/311.htm
Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.

I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.
Here's some possible solutions:
JQuery History
Salajax
A Better Ajax Back Button

Related

Distinguish between different types of beforeunload events

In JavaScript, is it possible to distinguish between beforeunload events that were triggered by the user closing a browser tab vs clicking a mailto link?
Basically, I would like to do this:
window.addEventListener("beforeunload", function (e) {
if(browserTabClosed) {
// Do one thing
}
else if (mailtoLinkClicked) {
// Do a different thing
}
}
Found a solution by looking at the event (e below) that gets passed in:
window.addEventListener("beforeunload", function (e) {
// We can use `e.target.activeElement.nodeName`
// to check what triggered the passed-in event.
// - If triggered by closing a browser tab: The value is "BODY"
// - If triggered by clicking a link: The value is "A"
const isLinkClicked = (e.target.activeElement.nodeName === "A");
// If triggered by clicking a link
if (isLinkClicked) {
// Do one thing
}
// If triggered by closing the browser tab
else {
// Do a different thing
}
}
The beforeunload method has an unstable behaviour between browsers, the reason is that browser implementations try to avoid popups and other malicious code runned inside this handler.
There is actually no general (cross-browser) way to detect what triggered the beforeunload event.
Said that, in your case you could just detect a click on the window to discriminate between the two required behaviours:
window.__exit_with_link = false;
window.addEventListener('click', function (e) {
// user clicked a link
var isLink = e.target.tagName.toLowerCase() === 'a';
// check if the link has this page as target:
// if is targeting a popup/iframe/blank page
// the beforeunload on this page
// would not be triggered anyway
var isSelf = !a.target.target || a.target.target.toLowerCase() === '_self';
if (isLink && isSelf) {
window.__exit_with_link = true;
// ensure reset after a little time
setTimeout(function(){ window.__exit_with_link = false; }, 50);
}
else { window.__exit_with_link = false; }
});
window.addEventListener('beforeunload', function (e) {
if (window.__exit_with_link) {
// the user exited the page by clicking a link
}
else {
// the user exited the page for any other reason
}
}
Obviously it is not the proper way, but still working.
At the same way, you could add other handlers to check other reasons the user left the page (eg. keyboard CTRL-R for refresh, etc.)

How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser

How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser using Javascript and not using Jquery Mobile library.
Solution would be really appreciated. I tried with few solutions online, but nothing seemed to work.
You should never do that. https://www.irt.org/script/311.htm
By the way, you may just warn the user using window.onbeforeunload.
You can-not actually disable browser back button. And there is no event for capturing the back button click.
If it is really necessary you can do something like that:
(function (global) {
var _extra_hash = "!";
var noBack = function () {
global.location.href += "#";
global.setTimeout(function () {
global.location.href += _extra_hash;
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _extra_hash) {
global.location.hash = _extra_hash;
}
};
global.onload = function () {
noBack();
// this is for disabling backspace on page except on input fields and textarea..
/*document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
};*/
}
})(window);
But the user can still kill the tab. Anyway, It is generally a bad idea overriding the default behavior of web browser.

Identify Click on browser close button for pop up message [duplicate]

This question already has answers here:
How to prevent closing browser window?
(4 answers)
Closed 8 years ago.
I am trying to implement the functionality to confirm whether "Leaving the page" whenever the user tries to close the browser.
As of now i have implemented,
function closeIt(e) {
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
}
window.onbeforeunload = closeIt;
This works fine for closing the browser, but instead works for all the links in the page aswell, as there is condition to identify what is causing the onbeforeunload event.
Can anyone help me identify them.
Thanks in advance.
Referring to various articles and doing some trial and errors, finally developed this idea which works perfectly for me just the way i wanted it to happen. The logic was quiet simpler it implement as well The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the Close('X') button.
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
return "";
}
//Edit start
var prevKey=""
$(document).keydown(function (e) {
if (e.key=="F5") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
window.onbeforeunload = ConfirmLeave;
}
prevKey = e.key.toUpperCase();
//Edit End
The ConfirmLeave function will give the pop up default message, it case there is any need to customize the message, return the text to be displayed instead of empty string.
Please note that the e.key returns undefined in some versions of chrome, so its better to use e.keyCode for key values and refer to http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes for values

iPhone Javascript Confirm Dialog Bug

I have a javascript confirm dialog popping up, but when I tap 'Cancel', then after the dialog closes, tap anywhere on the screen, the dialog pops up again. It only happens the one extra time, then you can tap on the page again without the dialog popping up.
I'm only seeing this on iPhone/iPad running iOS 5.0.1. I don't have an iOS 6 device, so I'm not sure it's happening there.
Here's the code I'm using:
$(bpm.remoteAppDivName).on('tap', 'a.delete-pending-payment', function(event) {
if (isJQMGhostClick(event)) { return false; }
var deleteGlobalPaymentURL = $(this).attr('href');
var confirmMsg = confirm ("Are you sure you want to do that?");
if (confirmMsg === true){
window.location = '/index.htm';
}
event.preventDefault();
return false;
});
var lastclickpoint, curclickpoint;
var isJQMGhostClick = function(event){
curclickpoint = event.clientX+'x'+event.clientY;
var ret=false;
if (lastclickpoint === curclickpoint) {
ret=true;
} else {
ret=false;
}
lastclickpoint = curclickpoint;
return ret;
}
Here's a link to the problem page: http://www.5280skateparks.com/dev/confirmBug.htm
Any help would be extremely appreciated.
UPDATE: I just confirmed that it's happening on iOS 6.0.1 as well.
This is the jQuery Mobile "Ghost Click" discussed in some detail here and here. On the forum page, a solution was proposed, which I have reproduced below with a small bug fix:
var lastclickpoint, curclickpoint;
var isJQMGhostClick = function(event){
curclickpoint = event.clientX+'x'+event.clientY;
var ret=false;
if (lastclickpoint === curclickpoint) {
ret=true;
} else {
ret=false;
}
lastclickpoint = curclickpoint;
return ret;
}
I have modified this code slightly to not always expect a pair of clicks. This function now works correctly in the case of 0 ghost clicks and more than 2 ghost clicks. You can use it by checking isJQMGhostClick(event) at the beginning of your tap handler and ignoring the event if the isJQMGhostClick function returns true.

Jquery hashchange problems in firefox

I am having a problem with the hashchange event in Firefox. We are using the JQuery hashchange plugin provided by Ben Alman. The code is as follows.
$(window).hashchange(function (e) {
alert("Hello");
//we want to perform a post in here.
});
var temp = "#123";
if (temp !== "") {
if (window.location.hash == temp) {
$(window).hashchange();
}
else{
window.location.hash = temp;
}
}
else {
window.location.hash = "#Home/Home";
};
Now this works fine in IE9 and Chrome, however in Firefox, I see the alert, but as soon as I click OK, the page refreshes, displays the alert again, and continues infinitely. Is there some sort of weird behaviour that Firefox uses that I am unaware of? Or is there simply some other problem that is hidden deeper?
In some browsers window.location.hash includes the # and in some don't so its better if your ignore it while comparing the hash value in your code.
Try this.
$(window).hashchange(function (e) {
alert("Hello");
//we want to perform a post in here.
});
//Remove hash from here which will be compared with window.location.hash
var temp = "123";
if (temp !== "") {
//Replace # by empty nothing
if (window.location.hash.replace('#', '') == temp) {
$(window).hashchange();
}
else{
window.location.hash = '#' + temp;//Now add the hash here
}
}
else {
window.location.hash = "#Home/Home";
};
We located the problem as occuring in MicrosoftAjax.js and found the following solution:
Firefox 6 Infinite Page Refresh With Page With Hash Tags

Categories