How do I listen for a browser back button click and call a function that I've defined and disable the normal behaviour of the back button? I'm using jQuery.
jQuery history plugin helps you to support back/forward buttons and bookmarks in your javascript applications. You can store the application state into URL hash and restore the state from it.
You could play with :
$(window).unload( function () { alert("Bye now!"); } );
.unload()
But this will be trigered when the user clicks a link that goes to another page , types a new address in the address bar or ... basicly it will be trigered whenever the user leaves the current page . I don't think you can stop the user from going away from you're page tough .
UPDATE:
unload() is now deprecated from jquery 1.8
Related
I want to redirect client to custom controller when he click back browser button.
Do you know any clear ways to catch back button event and force to call server?
Bests,
Thank you
Back button question is quite well answered on SO. A quick search will turn up lots of extra information. Here is a bit of a summary.
You have a few strategies to choose from.
1 - If you are developing an SPA (or not) you may find making use of the history api useful.
https://developer.mozilla.org/en-US/docs/Web/API/History
https://developer.mozilla.org/en-US/docs/Web/API/History_API
You will find plenty on SO about history api.
Try starting here Preserve dynamically changed HTML on back button
Basically, by adding a listener for popstate event which fires everytime the active history entry changes :
(in jQuery)
$(document).ready(function () {
$(window).on('popstate' , function (event) {
console.log('popstate');
console.log(event);
console.log(event.originalEvent);
});
};
http://caniuse.com/#search=history
2 - add a listner for the pageshow event, will fire when a page load is completed and when session history entry is used for navigation, so basically forward & back buttons.
https://developer.mozilla.org/en-US/docs/Web/Events/pageshow
$(window).on('pageshow' , function (event) {
console.log('pageshow');
console.log(event);
console.log(event.originalEvent);
});
http://caniuse.com/#search=pageshow
3 - Append a hashvalues to your urls with window.location.hash = 'pageHashValue'.
Listen for hashchange event and you can then act based on the #value if needed.
https://developer.mozilla.org/en-US/docs/Web/Events/hashchange
This is a common approach in single page applications.
$(window).on('hashchange' , function (event) {
console.log('hashchange');
console.log(event);
console.log(event.originalEvent);
console.log(window.location.hash);
});
http://caniuse.com/#search=hashchange
Finally take note that while you, as a developer, no doubt hate the browser back button (like me) our users tend to love it. If you change the expected behavior of the back button you can also expect your user experience to be negatively affected. The best strategy is to use these events to maintain the expected behavior of the back button rather than to try and change it.
I have a page where multiple tabs (subpages) are accessed via jQuery show/hide functions. When one clicks on the logo all other tabs are hidden and the first one is shown.
I would like to attach the same show/hide flow as with $("#logo").click() to the back button. When someone would tap browser's back button the default action should be prevented and show/hide combination should be activated to display the first tab.
Does anyone has a solution?
window.onbeforeunload function does not work...
https://jsfiddle.net/hqkyxz3w/3/
This is usually done using URL's hash (that's everything after #) and window.history.pushState() method.
When the user clicks on a tab/logo:
Change location.hash to whatever you want.
Call window.history.pushState() to add state to browsers history. See https://developer.mozilla.org/en-US/docs/Web/API/History_API for more detailed explanation what parameters it requires.
Call your function that hides/shows appropriate tabs.
Then, when you press the browser's back button you want the tabs to change so you need to know when the URL's hash has changed.
See this answer how to listen to hash change events: On - window.location.hash - Change?
Check current hash and call the same function from bullet point 3 in the previous paragraph that hide/shows tabs.
Here is the half working version... I have used location.hash and history.pushState to change it on clicking the tab and then window.onpopstate to hide the page..
https://jsfiddle.net/hqkyxz3w/4/
The problem still exists because the onpopstate also fires when clicking the tab and not only when tapping back button.. Here is the example:
https://jsfiddle.net/hqkyxz3w/5/
$("#tab1").click(function(){
location.hash = 'something';
history.pushState({extraData: "something"}, '', 'new-hash');
$("#page1").show();
});
$("#logo").click(function(){
$("#page1").hide();
});
window.onpopstate = function() {
alert('How to exclude it on clicking page one?');
$("#page1").hide();
};
I need to know whether user clicked the back navigation arrow in browser. I Used the below event but not occur this event while i am clicking the back navigation arrow.
$(window).on("navigate", function (event, data) {
});
please suggest your answer If you know.
You might use the popstate of the history.
The popstate event is only triggered by doing a browser action such as clicking on the back button (or calling history.back() in JavaScript). And the event is only triggered when the user navigates between two history entries for the same document.
You'll have to add a new entry to history with the same title and no change to the url
pushState(state, title, url)
and when you intercept the onpopstate you will do your desired actions, unbind the event and then use the history.back() api.
window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
window.onpopstate = null;
history.back();
};
history.pushState({}, document.title, "");
This is not a proven method I've tested it just in Chrome.
Short answer - you can't.
Long answer - yoooooooooooouuuuuuuuuu caaaaaaaaannnnnnnnnn't.
At least not in the way that I think you're looking for. Best you can do is detect when user is leaving the page - though that doesn't necessarily mean that the back button was clicked. Also, you can't stop them leaving the page.
window.onbeforeunload = function(){
return 'Leave this page?';
};
Using the onbeforeunload event, you can run some arbitrary code - but the browser will show a modal dialog box asking the user whether they want to leave the page or remain on the page. You can't override this.
My angular app's content creation flow is being broken by androids and browsers physical buttons which take the user to where they came from instead of previous step in the process. I tried fixing it with locationChangeStart as well as few other similar events, but they all get triggered both by my "Continue" buttons as well as physical "back" buttons.
Is there a way to trigger an event only when user presses browsers/android's back button, or alternatively to know if locationChangeStart was triggered by the back button vs app's button? If possible, I would like avoid adding jQuery as we are not currently using it.
I gave up on trying to detect the user pressing back button and act on it. Instead, make it the default action and change the way our buttons behave. I detect when user is pressing one of our buttons and set a variable based on it.
var navigating = false;
$scope.$on('$locationChangeStart', function(event) {
if($scope.global.application="new-ad" && !navigating){
event.preventDefault();
$scope.areYouSure = true;
}
});
$scope.nextStep = function() {
navigating = true;
$location.url('/step-two');
}
Basically, we first set our variable to false, and if the user presses physical back, it will display the prompt alerting user they will lose their work. However, if the user instead uses our "continue" button, also triggering the locationChange, it will set variable to true, letting the app know what the locationChange is triggered from within the app and allowing it to continue.
I'm building a custom confirmation popup which comes when ever user want to navigate from page without saving any detail. & I'm not able to find a right way to do this ?
Basically I have decided to put a function on window.beforeunload = func(e) event and use
e.preventDefault(); this syntax to prevent the redirect , actually the occurrence of event e. Now is there any way to re-fire the same event(It could be page redirect/ submit), If use clicks on the 'Ok' button.
You cannot use event.preventDefault() in window.onbeforeunload. You can only return dialogue for the onbeforeunload() function to give to the user.
https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload