How to change history like facebook viewer does?

I have a popup modal on my website similar to facebook photo viewer. When the modal is open, it displays content from another page, and I want to change the address bar value and history to show this.

There is a dropdown in the module that changes the content in a modal view to another page. When this happens, I want to change the address bar value and history again to show that the page has been changed.

Basically, I want to accurately reproduce the behavior of the facebook viewer you can try:

  • By clicking on this link
  • By clicking Photos

  • By clicking on the photo on the page
  • Press the right or left arrows (or use your keyboard arrow keys) to change iamges
  • a) click the back and forward buttons in the browser.
  • b) click from the photo viewer

I tried to create a JSFiddle to show where I am, but the JSFiddle does not seem to allow history manipulation. So I posted my code online here and you can download it here .


A few key points:

  • Start by browsing the index page, then use the link to navigate to the test page.
  • When the modal is closed, clicking the back button should not reopen the modal, but instead return you to the index page.
  • After closing the modal, pressing the forward button should resume the modal in its original state as the facebook photo viewer does
  • In my production code, the full url will change instead of adding / changing the variable in the url as shown in the demo code
+3


source to share


1 answer


You need to use history API and you need to use history.pushState()

history API

So when the user opens the modal way, you can do something:

history.pushState(stateObj, "page 2", "image\id.html");

      



Where: stateObj is the object you go through history, page 2 is the title, and the last parameter is the URL you want to change.

After that, you must use the popstate event as the browser's Back and Forward buttons do not reload the page.

+4


source







All Articles