vivek
vivek

Reputation: 347

What should be the new URL content when using Javascript History API?

I am using AJAX to load content dynamically, in my page. (basically I have a search bar, and the search results are obtained using AJAX). I want to make use of History API, since, After several searches(and also applying sorting and filter), if the user press browser back button, it takes them directly out of my site, instead of taking them to the previous search result. There are several online resources about using history API, but I could find any information regarding the URL, that needs to be set using

window.history.pushState(dataObj, title, URL);

If we just set any URL maybe like www.mypage.com/value1, then, this would become a fake URL, which if bookmarked and used later, will not work.

So I was thinking of using the following appoach.

1)Set the URL to www.mypage.com?variable1=value1&variable2=value2 ..... Where value1 and value2 ... would be some information, which I use for AJAX.(In my case these values would be the search text and the filter and sort information)

2)On press of back button, retrieve the URL, spit it using "?" and "&" separators, and take action accordingly

3)If this URL is bookmarked also, I can handle it appropriately, since all the information is available as variables.

So, My question is, Is this a right approach, or is there any better(standard) way of handling such scenario ?

Upvotes: 0

Views: 78

Answers (1)

Spencer D
Spencer D

Reputation: 3486

This is somewhat opinionated, but I think your approach sounds fine. So long as the user is able to press the back button and directly visit the URL to get the same results, then I think it is a perfectly fine way of doing it, and I cannot necessarily think of a better way.

In fact, from what I could grasp after looking into the Google search javascript code, it seems like they use a very similar method. They use history.pushState(...) to add search query URLs to browser history, and when they initialize the window, they check the history object as well as the URL to decide what search results to load using JS. That is not to say that Google is the go-to guru for proper web development, but if they are using a method like that, I think it is pretty safe to say that you would be fine to use it too.

I would definitely be interested if anyone has a better way, because that seems to be the best.

Upvotes: 1

Related Questions