Browser back button handling - javascript

I am trying to handle browser back button event but i could not find any solution.
I want to ask user if he clicks on browser back button using "confirm box" if he chooses ok i have to allow back button action else i have to stop back button action.
Can any one help me in implementing this.

Warn/confirm User if Back button is Pressed is as below.
window.onbeforeunload = function() { return "Your work will be lost."; };
You can get more information using below mentioned links.
Disable Back Button in Browser using JavaScript
I hope this will help to you.

You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

Related

Prevent browser back button navigation without page focus or touch

Without clicking/touching on anywhere inside page when click browser back button, navigation should be disable.
Below implementation only work when click inside page.
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () =>{ // not getting activate without clicking inside page
console.warn('DISABLE BROWSER NAVIGATION');
history.forward();
}
one of the best way is to open your application in a popup without controls but again depending upon your requirement this may not be applicable. Hope this helps. Something like below
function openPopup(){
var pathname = (window.location.pathname);
window.open(pathname+'openpagePopup.html','','width=800,height=450,toolbar=no, menubar=no,scrollbars=no,resizable=no,dependent,screenx=80,screeny=80,left=80,top=20,scrollbars=no');
return false;
}
The otherways are not trustworthy like you can show user an alert, but can not disable the back button, as per my knowledge. If you do the below make sure you check browser compatibility.
window.onbeforeunload = function() {
return "Write something here";
};
Update : I found there is a way to handle the page history. Incase that works, I have never tried, here is a link
JS - window.history - Delete a state

How can I warn user on back button click?

www.example.com/templates/create-template
I want to warn users if they leave create-template page. I mean whether they go to another page or to templates.
I use this code to warn users on a page reload and route changes should the form be dirty.
function preventPageReload() {
var warningMessage = 'Changes you made may not be saved';
if (ctrl.templateForm.$dirty && !confirm(warningMessage)) {
return false
}
}
$transitions.onStart({}, preventPageReload);
window.onbeforeunload = preventPageReload
It works as expected on a page reload and route changes if it is done by clicking on the menu or if you manually change it. However, when I click the back button, it does not fire the warning. only it does if I click the back button for the second time, reload the page, or change route manually.
I am using ui-router. When you click back button, you go from app.templates.create-template state to app.templates state.
How to warn if they press Back button?
First of all, you are using it wrong:
from https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload:
Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted
with; some don't display them at all. For a list of specific browsers, see the
Browser_compatibility section.
and
window.onbeforeunload = funcRef
funcRef is a reference to a function or a function expression.
The function should assign a string value to the returnValue property of the Event object and return the same string.
You cannot open any dialogs in onbeforeunload.
Because you don't need a confirm dialog with onbeforeunload. The browser will do that for you if the function returns a value other than null or undefined when you try to leave the page.
Now, as long as you are on the same page, onbeforeunload will not fire because technically you are still on the same page. In that case, you will need some function that fires before the state change where you can put your confirm dialog.
How you do that depends on the router that you are using. I am using ui-router in my current project and I have that check in the uiCanExit function.
Edit:
You can keep your preventPageReload for state changes in angular. But you need a different function for when the user enters a new address or tries to leave the page via link etc.
Example:
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}
However, you can use this as below:(using $transitions)
$transitions.onBefore({}, function(transition) {
return confirm("Are you sure you want to leave this page?");
});
Use $transitions.onBefore insteadof $transitions.onStart.
Hope this may help you. I haven't tested the solutions. This one also can help you.

Detect if the user arrived to the current page via the browser back button

I have a site where if a user navigates to a certain page then he gets a dialog notification depending on some condition on the page. The user can navigate to other pages from this page and of course can press the back button on those pages to navigate back to this page.
I'd like to detect if the user arrives via the back button to this page, so the dialog notification is not shown again (because the user has already seen it).
Is there a way to detect this reliably?
MDN list of window events
Your best possibility may be window.onpageshow = function(){};
An event handler property for pageshow events on the window.
window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};
Input trick is not longer working. Here's the solution I use:
if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
alert('Got here using the browser "Back" or "Forward" button.');
}
The best (although not TREMENDOUSLY reliable) way is to use the Javascript history object. You can look at the history.previous page to see if it's the next in the series. Not a great solution, but maybe the only way to figure it out.
I like use a value in an input field for this:-
<input type="hidden" id="fromHistory" value="" />
<script type="text/javascript">
if (document.getElementById('fromHistory').value == '') {
document.getElementById('fromHistory').value = 'fromHistory');
alert('Arrived here normally');
} else {
console.log('Arrived here from history, e.g. back or forward button');
}
</script>
This works because the browser repopulates the value of the field with the one the javascript puts in there if it navigates back to it from history :-)

Prevent back button load the hash in url instead on clicking a button

I have a website where the subscription form will appear when user click on a subscribe button and will add # to the url(http://signature-bravo.dev/#subscribe_form).
My question is how to make the page reload (usually when user click back button on browser) without showing the subscription form even the url is still http://signature-bravo.dev/#subscribe_form. It just appear when user click on a subscribe button.
How to archive this?
Thanks in advance!
If you are using jQuery this should work:
$(window).on('unload', function(){
window.location.hash = '';
});
It still leaves the '#', but nothing after.
If you don't want to use jQuery, you can use this code:
window.onunload=function(){
window.location.hash = '';
}

How to capture the destination url in onbeforeunload event

I want to use onbeforeunload to give a message to users before leaving certain pages.
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
Thanks
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
No, definitely not. The onbeforeunload event tells you only that the page is about to be unloaded, but not why.
It depends on how the user is leaving the page.
If they are typing an url in the address bar - then you're out of luck. As far a I know there's no way to capture the url of an address bar jump.
If they are clicking on a link contained somewhere on the page - that you can use the click event to capture the url and then decide how you want to handle things.
I posed a similar question
How can i get the destination url of a link on the web page in the javascript onbeforeunload event?
because I had a project to fix a wholesale order form. During the process of filling out an order my client's customers would go back to the catalog to check on a product's detail page and loose the current information on their order form.
By using the code below (which uses JQuery though I'm sure you could create the same thing in pure Javascript if you had to) I could tell when the user clicked a link that would leave the order form and then give them the option of opening the link in a new window/tab or loading the url in the current window and loosing their form data, or just returning to the form. This code works with all of the major browsers, at least their more recent versions.
$('body a').click(function(e) {
//if link references a page element
if ($(this).attr('href').charAt(0)=="#") {
return;
}
//check if link is to same window
var pathname = window.location.pathname;
var pathname2 = $(this).attr('href');
pathname2 = pathname2.replace(/^.+\.\//, '');
if (pathname.indexOf(pathname2) >= 0) {
//link clicked is contained on same page
//prevent page from getting reloaded & losing data
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
return;
}
//link clicked on is another page
if (hasMerchandise) { //var to indicate user has items on order form
//give user options: leave page, open link in other page, stay, etc.
// $('.popupForm-handleExitRequest').click(); //roll your own code
//prevent page from getting reloaded & losing data
//in case user wants to cancel page change or open link in another window
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
} else {
//load new page
$(this).removeAttr('target');
}
});

Categories

Resources