Handle browser back button with angular in controller - javascript

I want to handle browser back button with angular, i have tried many solution but i cant find one which is fulfill my requirement,
here is my tried code.
$scope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
if(!allowed /* inject your logic here */) {
event.preventDefault();
}
});
it is working fine when i go to particular page from my app, but if go from e.g www.google.com direct to that particular page by pasting link then it just get back to Google.
what is actually i want handle both scenario of back button.
is it possible?
I will really appreciate your response,
these are the links I have tried but problem remain same.
How to detect browser back button click event using angular?
How to handle browser back button event in a particular controller?

Have you tried using 'window.onbeforeunload'?
For example:
window.onbeforeunload = function()
{
//Do whatever here for example prompt user
return "Are you sure you want to go back?";
};

Related

Define a reference site for the history.back button

We want to have a back button in our site
but history.back in javascript does not help us.
We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.
In fact, we want a return button to run on our site only.
my code is
<i class="fas fa-arrow-left"></i><span class="btn-text">Back</span>
This only works for your own made back button and won't work with the browser back button
There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.
1- The simple method
You use document.referrer and ensure the domain is yours before calling history.back().
2- The complex method
You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.
This code checks the history of back button of the browser on its click event:
$('#backbtn').click(function () {
if (document.referrer.includes(window.location.hostname)) {
window.history.back();
} else {
window.location.href = "/your/path";
}
});

How to stop unloading the page?

I have a page where user needs to enter some data and click save to validate the changes, but my problem is if the user is trying to close the browser window or click on a different link to navigate to a different page..I need to delete all the entries the user has saved so far..
I am doing it the following way
window.onbeforeunload = function()
{
if(confirm('Are you sure you want to navigate'))
{
//Invoke `enter code here`server side method
}
else
{
// return false;
}
}
Everything works fine if he click on Yes, the problem comes when he click on "No"..Even if he click on No..the page unload method is getting called and it is redirected to a different page..but I want it to stay in the same page in same state...can you please help me in achieving this.
Thanks and appreciate your response....
You cannot stop the user from leaving the page. What you can do is alert a message to them, asking if they want to leave or not.
The window.onbeforeunload event should return a string (and only a string). This string will be printed on the alert box made by the browser.
You cannot use your own alert box, or block the user from leaving (or redirect them).
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
When a user leaves the page, you can use the onunload event to make an AJAX call (you may need to use async: false here).
Example:
$(window).unload(function(){
$.ajax({
url: '/path/to/page/',
async: false, // this may be needed to make sure the browser doesn't
// unload before this is done
success: function(){
// Do something
}
});
});
NOTE: Instead of doing this, why don't you just save everything when the user is completed? Instead of saving it and then removing it if the user doesn't finish?
First of all: you can't! It's impossible. onbeforeunload only accepts a string as return value and will then close if the user wants that.
But then think about what happens if the computer is being without energy and shuts down? Or the browser will closed by the Task Manager? Or even more "realistic": The internet connection get lost! => Then you got invalid data states too!
You are trying to solve a false problem! Your problem isn't this function, your problem is the state of your formular!
Why do you need some kind of function? Do you saving the data before he clicks on save? Then don't! Or make sure to have another query which detects unfinished data in your database and delete it after a timeout!
onbeforeunload only accepts a string as return value. That string will be displayed by the browser with the option to stay on the page or leave it. But that's ll you can do.
You can use something like this, just call the following function on your page
function noBack() {
window.onbeforeunload = function(){window.history.forward()}
}
this disables Back button if window.history is clean, otherwise it works only first time.

Detect/Warn when back button is pressed

Is there a way detect/catch the browser back button being pressed and in doing so ask them if they are sure about going back?
Building an application and it will soon be converted to an ajax based application and per requirements it's supposed to reset the application if a user goes 'back'...
I mainly want this to catch the accidental back button presses as I personally feel that if someone can't follow the directions that are given to them at the beginning of the application.... I'm not worried about their extra work.
If there isn't a way to do this is would the best solution be to launch the application in a new window/tab so that there is no history for it to go back to?
you can use onbeforeunload to detect back button or accidental page navigations:
window.addEventListener("beforeunload", function() {
var ans = confirm("Are you sure?");
if (ans) {
//TODO: add your code here
}
}, false);
to replace the current page in browser history you can use window.location.replace():
window.location.replace("yourNewURL");
You can also set the onbeforeunload function like this:
window.onbeforeunload = function() {
return "Are you sure you wish to leave?";
};

Canceling a back or forward event that causes a hash change or an HTML 5 history change

Is it possible to cancel a browser back or forward event that causes a hash change or an HTML 5 history change in the same way that one can cancel a page-loading back or forward event through window.onbeforeunload?
I don't know if it helps in your situation but Sammy.js, a popular hash-routing library, has a before handler. I've used it in my application to record the previously accessed hash, and if it's the hash I want to stop them from leaving, return false will keep them on that page. You still need to rewrite the URL to display the previous page, but it seems to be working. Here's a little sample of what I did:
app.before(function (context) {
if (context.path === lastRoute) return false; // Was fired from our app.setLocation below.
if (lastRoute === "/#MyHashWhereIFirstWantToConfirm") {
if (!confirm("Are you sure you wish to leave this page?")) {
app.setLocation(lastRoute); // Send them back to /#MyHashWhereIFirstWantToConfirm
return false; // Keep the handler for the destination page from firing.
}
}
lastRoute = context.path;
return true;
});
Used in conjunction with window.onbeforeunload you could pretty well keep the user from leaving the page without a confirmation.

Implement a Back-Button 'Warning' in Javascript for use in Flex

I have a Flex application where I want to give the user a warning if they hit the back-button so they don't mistakenly leave the app. I know this can't be done entirely in Actionscript due to cross-browser incompatibility. What I'm looking for is just the Javascript implementation to catch the back-button.
Does anyone have a simple non-library cross-browser script to catch the back-button? I can't seem to find a post that shows an example.
You can use the window.onbeforeunload event.
window.onbeforeunload = function () {
return "Are you sure you want to leave my glorious Flex app?"
}
The user can press okay to leave, cancel to stay.
As you stated, this throws the alert any time the page changes. In order to make sure it only happens on a back button click, we have to eliminate the alert message whenever they're leaving the page from natural, expected sources.
var okayToLeave = false;
window.onbeforeunload = function () {
if (!okayToLeave) {
return "Are you sure you want to leave my glorious Flex app?"
}
}
function OkayToLeave() {
okayToLeave = true;
}
You'll have the responsibility of setting the variable to true whenever they click a button or link that will take them from that page naturally. I'd use a function for unobtrusive javascript.
Set your event handlers in the DOM ready:
referenceToElement.addEventListener('onClick', OkayToLeave(), false);
This is untested, but should point you in the right direction. Although it may seem like a nuisance to do this, I imagine it's more complete functionality. It covers the cases where a user may click on a favorite, or be redirected from an external application.

Categories