问题
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:
- Clicking on this link
- Clicking on
Photos
- Clicking on a photo on the page
- Click the right or left arrows (or use your keyboard arrow keys) to change iamges
- a) click the back and forward history buttons in your browser
- 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
回答1:
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.
来源:https://stackoverflow.com/questions/27572523/how-to-modify-history-as-facebooks-photo-viewer-does