Angular 2: Reload current page on browser back / forward / refresh - javascript

Been doing some research, is there any way to just reload the current page on user clicking the browser back button or forward? For SPA.
I know it is not recommended to restrict users from using their browser buttons and probably not much control of them either.
I was looking into something like this:
#HostListener('window:beforeunload', ['$event'])
onPopState(event) {
console.log("Back Button detected!");
window.history.forward();
}
Update: This is closer to what I want to achieve, but if the user spams the back button, he can potentially get back to a previous screen in SPA. (I am not using { skipLocationChange: true } so that may resolve that issue.
<script>
history.pushState(null, null, location.href);
window.onpopstate = function (event) {
history.go(1);
};
</script>

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

Enable forward button while disabling browser back button

I disabled browser back button using the following code on load of page
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
Code is working fine.I am not able to proceed for previous pages. But forward button is also disabled. I have to enable forward button on the page.
You are forcing to update url manually by using history.pushState. If you use history.pushState, it clears forward state's history.
Hence window.history.forward() returns undefined. So you cannot go to forward direction.
Kindly use warning instead of disabling back button,
window.onbeforeunload = function() {
return "some text"
};

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 :-)

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

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)

Call a function on page refresh using Javascript

function warnuser()
{
return "Don't refresh the page.";
}
window.onbeforeunload = warnuser;
If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not!
I am confused about how to do that.
Thank you
You need to intercept the F5 key press and setup the onbeforeunload handler only in that case:
document.addEventListener('keydown', function(e) {
if(e.which == 116) {
window.onbeforeunload = function() {
window.onbeforeunload = null;
return "Do you really want to refresh the page?";
}
}
}, false);
Demo: http://jsfiddle.net/ejDrq/
Note that this does not work if the user clicks the Refresh button. It is impossible to intercept this.
If you have control of the server side which is hosting the page then you can handle this logically with a semaphore (wiki:semaphore). Basically it is a spinning lock which would be implemented in their server side session. Resetting the page state if they have entered and not exited in a safe manner. Naturally, as with all spinning locks, there would have to be a safe state to clear the lock out.

Categories

Resources