简体   繁体   中英

How to modify history as facebook's photo viewer does?

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

There is a dropdown in the modal that changes the content in the modal to that of a different page. When this happens, I once again want to change the address bar value and history to show the page was changed.

Essentially, I want to exactly replicate the behavior of facebook's photo viewer , which you can try out by:

  1. Clicking on this link
  2. Clicking on Photos
  3. Clicking on a photo on the page
  4. Click the right or left arrows (or use your keyboard arrow keys) to change iamges
  5. a) click the back and forward history buttons in your browser
  6. b) click out of the photo viewer

I tried to create a JSFiddle to show where I am at with this, but JSFiddle apparently does not allow the history to be manipulated. As such, I've put my code online here , and which you can download from here .


A few key points:

  • Start by viewing the index page, then use the link to go to the test page
  • When the modal is closed, pressing the back button should not reopen the modal, but instead should take you back to the index page.
  • After closing the modal, pressing the forward button should reopen the modal in it's original state as facebook's photo viewer does
  • In my production code, the full URL will be changed instead of adding/changing a variable in the URL as shown in the demo code

You have to use history API, and specifically you have to use history.pushState() history API

So when a user opens the modal you can do something :

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

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

After you've done so you have to use on popstate event as the browser Back and Forward buttons won't reload the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM