How to handle / prevent browser navigation or reload in angularjs? - javascript

I would like to detect in my angular app when a user is navigating away from or reloading a page.
App (that uses some login process) should then distinguish that it was re-loaded, so user won't lose his auth data and app should be able to restore then necessary information from localStorage.
Please suggest some best techniques to "handle" browser reloading / navigation.

All of your javascript and in memory variables disappear on reload. In js, you know the page was reloaded when the code is running again for the first time.
To handle the reload itself (which includes hitting F5) and to take action before it reloads or even cancel, use 'beforeunload' event.
var windowElement = angular.element($window);
windowElement.on('beforeunload', function (event) {
// do whatever you want in here before the page unloads.
// the following line of code will prevent reload or navigating away.
event.preventDefault();
});

I had the same problem, but Ben's answer didn't work for me.
This answer put me on the right track. I wanted to add a warning on some states but not all of them. Here is how I did it (probably not the cleanest way) :
window.onbeforeunload = function(event) {
if ($state.current.controller === 'ReloadWarningController') {
// Ask the user if he wants to reload
return 'Are you sure you want to reload?'
} else {
// Allow reload without any alert
event.preventDefault()
}
};
(in the ReloadWarningController definition, which had the $state injected)

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.

Prevent user to navigate away with unsaved changes

I'm currently using Backbone.Marionette to create a SPA and in one of the views it is possible for the user to navigate away with unsaved changes. I can control some of these events, like buttons and menu options within the view that would take the user away, but some others would require to manipulate either Backbone.Router or work with the DOM events directly.
I already tried listening to beforeunload (doesn't work as the application is still loaded) and hashchange (doesn't work as you cannot stop the browser from navigating away). These solutions (1, 2, 3) don't work in this case, the Javascript is never unloaded.
Changing the Backbone.Router seems to be the best option, but because of how it is initialized I don't think it is possible to introduce this feature or at least I cannot find a way of doing it. This solution, for example, doesn't work because hashchange is not cancelable (you cannot call stopPropagation on it), and this other solution doesn't work because navigate is not defined on the Backbone.Router object.
Any suggestions?
I've managed to find a solution to this, although some more work is required. For this solution, I am assuming that you keep track when a view is dirty.
There are 4 main ways of moving out of a view;
Click on a link on the view
Click on link outside the view
Click on refresh or external link
Click on back/forward on the browser
1. Application link
This is the easiest case. When you click on your own link, you have to check if your view is dirty. For example, I have an in-app back button that is handled by a historyBack function. On the view:
historyBack: function() {
if (this.isDirty) {
answer = confirm("There are unsaved changes.\n\nDo you wish to continue?")
if (answer) {
this.isDirty = false
window.history.back()
}
}
else {
window.history.back()
}
}
2. Links outside your view
This type of interaction can be handled by extending the Router prototype's execute method, not the navigate method as proposed in other places.
There should be a variable somewhere accessible by the Router that stores the state of the view. In my case, I'm using the Router itself and I update this variable every time I change the dirty flag on the view.
The code should look something like this:
_.extend(Backbone.Router.prototype, {
execute: function (callback, args, name) {
if (Backbone.Router.isDirty) {
answer = confirm "There are unsaved changes.\n\nDo you wish to continue?";
if (!answer) {
return false;
}
}
Backbone.Router.isDirty = false
if (callback) callback.apply(this, args)
}
}
3. Refresh or external link
Refresh and external links actually unload your Javascript so here the solutions based on beforeunload (see question) actually work. Wherever you manage your view, I use a controller but let's assume it's on the same view, you add a listener on show and remove it on destroy:
onShow: function() {
$(window).bind("beforeunload", function (e) {
if (this.isDirty) {
return "There are unsaved changes.";
}
}
}
onDestroy: function() {
$(window).unbind("beforeunload");
}
4. Back/Forward on the browser
This is the trickiest case and the one I haven't figured out completely yet. When hitting back/forward, the user can navigate out of the app or within the app, both cases are covered by the code on 1 and 3, but there is an issue I can't figure out and I will create another question for it.
When hitting back/forward, the browser changes the address bar before calling the router so you end up with an inconsistent state: The address bar shows a different route to the application state. This is a big issue, if the user clicks again on the back button, after saving or discarding the changes, she will be taken to another route, not the previous one.
Everything else works fine, it shows a pop up asking the user if she wants to leave or continue and doesn't reload the view if the user chooses to stay.

Angularjs handling leaving a template in various ways?

I am trying to implement a function in my angular module that will fire an event that saves the changes on the page. The different ways a user can leave the page is:
Clicking a link that loads a new template.
Clicking the back button
Closing the tab/window
My implementation handles #1 using this code:
.directive('confirmOnExit', function() {
return {
link: function($scope, elem, attrs) {
window.onbeforeunload = function(){
return "If you leave this page, you will exit the practice session. You will be able to view your score report for the completed session but will have to start a new one if you want to continue practicing.";
}
$scope.$on('$locationChangeStart', function(event, next, current) {
if($scope.$dirty & confirm("Are you sure you want to leave this practice session?")) {
console.log("Will end session!");
end_session();
}
});
}
};
});
However, when #2 or #3 occur, the pop up dialog shows up but it seems like it is not triggering the end_session() function.
Any insights into how to deal with the back button and closing the tab/window would be appreciated?
Sounds to me like a race condition. end_session() might not be firing before the browser successfully unloads the page, but without more code I can't really help, since I'm not sure what end_session() does.
What you could do is capture the locationChangeStart and defer it until after all of your unload tasks are complete.
A quick note, directly referencing window is an Angular "anti-pattern" of sorts:
https://docs.angularjs.org/api/ng/service/$window

Prevent user from accidentally navigating away

My problem is a bit more complex than using the following simple JavaScript code:
window.onbeforeunload = function (e) {
return 'Are You Sure?';
};
On an e-commerce web page I would like to remind the user that he has items in the shopping cart so that he can change his mind before
closing the browser tab/window
navigating to another domain
The JavaScript method above does not solve my problem because it is evoked even when the user navigates within the domain.
Short:
User tries to close window -> Show dialog
User changes www.mydomain.com/shoppingcart url to www.google.com in the browser's address bar -> Show dialog
User navigates to www.mydomain.com/checkout with the checkout button or presses the back button in the browser -> Do NOT show the dialog
It's not possible to tell if a user is pressing the back-button or closing the tab and you don't have access to their intended location.
It is possible to stop the dialog from showing if an internal link is clicked though:
(function(){
function isExternal( href ) {
return RegExp('https?:\\/\\/(?!' + window.location.hostname + ')').test(href);
}
var returnValue = 'Are you sure?';
document.documentElement.onclick = function(e){
var target = e ? e.target : window.event.srcElement;
if (target.href && !isExternal(target.href)) {
returnValue = undefined;
}
};
window.onbeforeunload = function(){
return returnValue;
};
})();
Sorry there's no technical solution to your "problem."
It's not an accident when a user decides to leave your site, i.e. by typing a new URL, so stopping them to say "Hey, you haven't checked out yet" is kind of pointless.
I would suggest letting the visitor leave your website freely and simply remembering their information (DB, Sessions vars, etc). In terms of eCommerce that is the polite way of keeping customers.
If someone wants to leave your website, they will. Double-checking beforehand will likely only irritate the customer and lessen your chance of their return.
Since the beforeUnload-event object does NOT contain the location the user is trying to go to, one "hack" to do this would be to add click listeners to all links on your site, and disable the unload-listener in that handler. It's not very pretty, and it will probably not work if the user navigates with the keyboard, but it's my best guess at the moment.
It sounds like you'd need to use an onbeforeunload and then modify all your internal links to disable it. Probably the thing to do for the latter would be a jQuery event; making the actual hrefs run through JS would be terrible, not least because it'd defeat search engine crawling.
I was looking into this too, reason being we have some really stupid end users who fill out a whole web form then don't press the save button.
I found this is u r interested, seems like a good solution:
https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

Categories

Resources