Handling browser back or forward button clicks for ajax content

Author - Harleen Kaur
17.04.2018
|
0 Comments
|

In Jquery / Javascript how to handle updates for partial (nested) web page view Inside a single View on browser back, forward & refresh button events? Or simply put how to handle browser back or forward button clicks for content displayed dynamically or with ajax calls?

Suppose when we want to load different views conditionally inside a single view. In other words, we are rendering nested view inside a single view/page based on menu items click in the parent view. In this case, if I click on the back button or forward button of the browser, it will not work as usual when we navigate from one page to another in web application and the way it saves the navigation history of different pages.

So for the case, when we are on the same page, but we are setting the nested view dynamically based on condition, we need some identifying criteria for each different nested view in the same page/View.

For identification purpose, we use the concept of Fragment URLs. In simpler words, we will use the concept of hash-based URLs which contain the character of sequences preceded by # at the end of actual Url of page/View. For each different nested view inside a single view which is set conditionally, we can append different character sequences preceded by #. The benefit of using this technique is that these are stored in the browser history and with this, if we click on back & forward buttons, the page is not refreshed and only the characters sequences changes, that we can handle partial view updates on the Page on browser events.

Suppose I have Main View as Parent View and I have different buttons in the menu for rendering different partial views through Ajax in a Div with id ‘myPartialView’. Below is the sample cshtml code :
_____________________________________________________________________________________________
Cshtml View:
_____________________________________________________________________________________________


____________________________________________________________________________
Below is is the javascript function called to set the partial view into the div with id myPartialView through ajax and also append the character of sequences followed by hash character.
___________________________________________________________________________

Javacript/Jquery Code:
____________________________________________________________________________

function setPartialView(e) {
var partialViewUrl = '';
var menuItemId= $(e).attr('id');
var hashIndex= $(e).data('hashurl'); // Retrieve the element id & its hash followed characters
switch (menuItemId) {
case "home":
partialViewUrl = "/Home/Index";
break;
case "aboutus":
partialViewUrl = "/AboutUs/Index";
break;
case "services":
partialViewUrl = "/Services/Index";
break;
case "portfolio":
partialViewUrl = "/Portfolio/Index";
break;
case "career":
partialViewUrl = "/Career/Index" ;
break;
case "contactus":
partialViewUrl = "/ContactUs/Index";
break;
Default:
hashIndex=”#home”;
partialViewUrl = "/Home/Index";
}
$.get(partialViewUrl, function (data) {
$("#myPartialView").html(data);
window.history.replaceState(null, null, hashIndex );
// used to append the custom character sequences to page ( in general manipulates browser
history )
sessionStorage.setItem('oldState', hashIndex );
// hash preceded sequence of characters are stored in sessionstorage to handle browser refresh
event
});
}

___________________________________________________________________________

Screenshot below shows how urls appear using hash based technique:

Following javascript/jquery code on document ready function of Parent Main View Page handles the first time load of page and refresh button events from browser. When first time page is loaded there will not be any sessionstorage variable of ‘oldstate’. So else condition will be fired and default case will from the setPartialView() method. But when the page is refreshed from browser button then we will have the sessionstorage value, based on this value we will render that specific partial/nested view into the Parent View.
____________________________________________________________________________

$(document).ready(function () {
var oldPageState = sessionStorage.getItem('oldState');
if (oldPageState) {
var menuElement = $("#menu").find("[data-hashurl='" + oldPageState + "']");
setPartialView(menuElement);
}
else {
setPartialView();
}
});

____________________________________________________________________________
Benefit of appending these special character sequences is that these are maintained in the browser history. So if we click back or forward buttons on browser accordingly its hash preceded character sequences will change and in this case page will not be reloaded, only these special character sequences will change. So based on this change in the url, we can handle the rendering of partial view on browser button events without reload of complete page.

To detect the change in the url of view, jquery comes with hashchange event. Below is the jquery code of hashchange event that will be triggered on change of hash preceded sequence of characters in the url.
____________________________________________________________________________

$(window).on('hashchange ', function () { // Event will get fired on browser back & forward button click
var oldState = sessionStorage.getItem('oldState');
var windowLocation = window.location.href;
var currentState = windowLocation.substring(windowLocation.indexOf('#'));
if (currentState.length > 1) { // this check is added to avoid different browser related issues.
if (currentState != oldState) { // this check is also added to avoid different browser related issues.
var element = $("#menu").find("[data-hashurl='" + currentState + "']");
// finds the anchor element based on hash url word and passes it to method to set partial View
setPartialView(element);
}
}
});

In the above code, I have added the condition current state length, because some browsers behave differently. Like in Firefox, when I click on anchor link from the menu, URL hash preceded characters gets automatically replaced by single #, hashchange events get fired before setting the new nested/partial View and its corresponding hash word.

This technique is useful for Ajax-based applications and single Page applications when we want to avoid reloads of page navigation and we want to store the states on a single Page.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *