Thursday 12 July 2018

Solution to browser back button click event handling

In Javascriptonbeforeunload event is fired when the page is about to unload and there can be multiple reasons for this unload. For instance, back or forward or refresh button is clicked or a link on the page is clicked etc.
Normally, onbeforeunload event is used in order to handle browser back button functionality as follows:
But there is a problem that identical event occurs once a user clicks on refresh button of a browser. So, to grasp whether or not refresh button or back button is clicked, we will use the subsequent code.
Above code snippet works well in browsers aside from FireFox, In case of FireFox, we need to apply the following check.
So, consolidated code snippet will look as:
Above code snippet is beneficial in many scenarios however there are some issues with it. For instance, navigation can be done using keyboard keys and refresh can also be done using F5 or CTRL+R which can not be handled using above code.