i want disable browser back button and refresh button. in angular
example my source
page source :
"use strict";
.controller("wizardSecondController", function($scope, $state, $stateParams, wizardManager) {
$scope.$on("$viewContentLoaded", function(event, data) {
});
i want prevent browser back and refresh .
please answer .
If you want to disable browser back button in angular, please try out the following code. It may help.
$scope.$on('$locationChangeStart', function(event, next, current){
event.preventDefault();
});
It's not a very straight forward thing in Angular.js but you can use JavaScript function - window.onhashchange to disable to back button.
Take a look at this link, you might get better ideas.
Use javascript event
window.onbeforeunload = function(e) {
var dialogText = 'Dialog text here';
e.returnValue = dialogText;
return dialogText;
};
refer
I shall give you advice as to disabling the back button:
Strictly speaking it isn't "possible" if using standards, but there are workarounds.
There is the window.history object which includes a small API.
But it doesn't allow you to double check for states/pages before the user surfed to your site. Obviously for security reasons and not by accident or missing implementation.
There's various checks for the usage of navigating back in the history and several posts about that topic, but none is helpful as to when it comes to the point the user leaves your page and goes beyond your accessible history.
As to that, check on the events
onhashchange
onpopstate (be aware IEs implementation thereof is half-baked, even in IE11 --> in my case it didn't respond to mouse interaction, only to js history.*()
If you want to catch the user on your site for some hopefully incredibly good purpose:
Create a duplicate entry of your home page on the first homepage-hit via window.history.pushState and instantly window.history.forward() --- (this works especially well and unnoticable on SPAs)
Reiterate that procedure every time the user navigates to your homepage/lowest_level_parent_state ...
Et voila ...
In my case I can't even escape our page if I hold down the backspace button ...
Another convenient option would be to put the page into fullscreen mode if feasible :)
Cheers, J
Related
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.
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)
I'll start this off with I have researched a bit, but no solution that solves what seems like it should be a simple JQM modification.
I have a wine review webapp that has the following view user flow:
http://5buckchuck.com/
Wine type > Wine list > Wine Details > Wine review (redirect via django backto ) > Wine Details updated from review
What I want to happen is when the user presses the back button it should go back to the wine list. What currently happens is the the Wine Detail view is reloaded. It takes pressing back three times to get back to the Wine List. :-(
My thoughts to solve this were two:
Splice the last 3 items from the history stack, if the last items in the history stack was Wine Review. I had a hard time trying to introspect the last history object to get the pageURL. I have a feeling that this solution is a bit too fragile though.
var last_hist = $.mobile.urlHistory.getActive();
last_hist.data.pageURL;
The second thought was to override the back button behavior so that the back button from the Wine Detail view would always go back to the Wine list view
$('div#wine_detail').live('pageshow',function(event, ui){
$("a.ui-btn-left").bind("click", function(){
location.replace("/wines/{{wine.wine_type}}/#");
});
});
There is probably a better way to do this, but I'm a bit out of ideas.
Update:
So I continue to hack on this with somewhat negligible results. On thing I have found was this is what I basically need to work: window.history.go(-3)
from the console it does exactly what I need.
So I tried binding it the the back button like such:
$('div#wine_detail').live('pageshow',function(event, ui){
var last = $.mobile.urlHistory.stack.length - 1;
var last_url = $.mobile.urlHistory.stack[last].url;
var review_url = /review/g;
if (last_url.match(review_url) )
{
$('div#wine_detail a.ui-btn-left').bind( 'click', function( ) {
console.log("click should be bound and going back in time...")
window.history.go(-2);
});
}
else
{
console.log('err nope its: ' + last_url);
}
});
No dice, something interupts the transaction...
I'd prefer not to splice/pop/push with the urlHistory. How about redirect on pagebeforechange like so:
$(document).on("pagebeforechange", function (e, data) {
var overrideToPage;
// some for-loop to go through the urlHistory TOP>DOWN
for (var i = $.mobile.urlHistory.activeIndex - 1; i >= 0; i--) {
// this checks if # = your target id. You probably need to adapt this;
if ($.mobile.urlHistory.stack[i].url = $('#yourPageId').attr('id')) {
// save and break
overrideToPage = $.mobile.urlHistory.stack[i].url;
break;
}
// set new Page
data.toPage = overrideToPage;
}
});
This captures your back button changePage call and redirects to the page you want. You could also just set data.toPage = winelist directly of course.
I'm only doing this with #internal pages, but it shoudn't be so hard to set this up with winelist.html etc.
For more info, check the event page in the JQM docs
Why not have a back button in the header section of your page? Something like this:
<div data-role="header">
<a data-direction="reverse" data-role="button" href="#winelist" data-icon="back">Back</a>
<h1>Wine Detail</h1>
</div><!-- /header -->
I wrestled with this recently as well. After thinking about it, I realized I could rewrite my JQM application to use Pop Up "windows" for those pages that I didn't want in my history. This ended up being an easier and cleaner fix than mucking around with browser history.
Now users can intuitively use the browser back button, and I don't have to code application back buttons.
The only thing you have to ensure is that the popups don't themselves make it into the browser history, so make sure to set the "history" option to false like so:
$('#some_popup').popup( { history: false } );
Okay so the solution was close to the update I posted. The issue with the previous solution was that there were to many things bind-ed to the "Back" button. While my new bind action may have been working sometimes, the other actions would take place too, I tried unbind() but still no worky.
My solution is a bit of smoke and mirrors. I check to see if the the previous page was the review page and then if so, I swap out the old back button for my new faux button with the history back step like so:
$('div#wine_detail').live('pageshow',function(event, ui){
var last = $.mobile.urlHistory.stack.length - 1;
var last_url = $.mobile.urlHistory.stack[last].url;
var review_url = /review/g;
if (last_url.match(review_url) )
{
$('a.ui-btn-left').replaceWith('<span class="ui-btn-inner ui-btn-corner-all"><span class="ui-btn-text">Back</span><span class="ui-icon ui-icon-arrow-l ui-icon-shadow"></span></span>');
$('#time_machine').bind( 'click', function( ) {
console.log("click should be bound and going back in time...")
window.history.go(-3);
});
}
else
{
console.log('err nope its: ' + last_url);
}
It looks exactly the same, and no one is the wiser. it could probably be improved by using the the jQm method pagebeforeshow so user could never see the swap. Hope this helps someone.
If you have the situation that you want the close button refer to an arbitrary (not the last) page, you could also change first to the target page and open the dialog afterwards. Therefore the close button at the dialog will open the target page.
// First: change to the target page
$.mobile.changePage('#target_page');
Afterwards open the dialog like this.
// Second: change to the dialog
window.setTimeout(
// for some reason you have to wrap it in a timeout
function(){
$.mobile.changePage('#dialog');
},
1
);
Now you can open the dialog and the close button will open #target_page.
Advantages:
solution works for single dialogs rather than removing all close buttons from all dialogs
seamless integration on a single point of code
history manipulation is not needed
I have seen similar issues before when using jquery mobile and it is addressed in the documentation. When setting up your Javascript "at the beginning of your page" use pageinit instead of ready or maybe in your case pageshow. I think this will address your issue without having to workaround the history queue.
I'm working on an ASP.NET Web Project with some AJAX magic. As my GridView's data needs up to 15 seconds to be gathered, I send the page to the client and fire an asynchronous update of an UpdatePanel via jQuery/JScript (see below).
This works well, so far. Now I'd like to skip this step when the user navigates to the next page (e.g. record detail view) and comes back via the "Back" button. Is there a way to get his, and what's the most elegant one?
This one does not work (hasDonePostBack's value isn't kept by the browser):
var hasDonePostBack = false;
function fRefreshAsyncOnce(id, param) {
$(document).ready(function() {
if (!hasDonePostBack) {
__doPostBack(id, param);
hasDonePostBack = true;
}
});
}
Any help would be great!
The reason why this is important: Regetting the data takes another 15 seconds. Moreover, the grid is working with controls and more client script (e.g. checkboxes that can be checked, CSS classes that are toggled, etc.), and all this should be the same after returning.
Cheers,
Matthias
You may want to look at the history point feature; you may be able to take advantage of that for this feature: http://msdn.microsoft.com/en-us/library/cc488548.aspx
However, that is the nature of the beast when triggering client-side operations... the other option is allowing the user to cancel the postback (or try to interpret a way to cancel it yourself) using this technique: http://msdn.microsoft.com/en-us/library/bb398789.aspx
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