Change url via JavaScript (no hash-tag)

2019-03-13 09:34发布

问题:

I'm wondering how does facebook change the url when I switch between pictures in a album? There is no hash-tag, just a real url.

Example: The current url: facebook.com/photo.php?fbid=XXXXXX1 and if I click next, the url changes to facebook.com/photo.php?fbid=XXXXXX2

Does anybody know how to realize this with JavaScript?

回答1:

Yes. Check out https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries

It pushes a new history state (an HTML5 thing) instead of using the hash key.



回答2:

My first hunch would be:

document.location = facebook.com/photo.php?fbid=XXXXXX2;

With some way of preventing the default reload page action.



回答3:

Summerizing all the answers,

we can say (I'm not a FB coder) that Facebook uses:

  • the HTML5 window.history.pushState / replaceState / popState methods on browser that support these methods (I think one is Chrome). In this way Facebook changes the real url (not just the part after the # character).

  • On other browsers, that do not support these new HTML5 methods (like IE6 / IE7 and IE8), Facebook simply changes the part of the url after the # character, by simply setting the the window.location.hash property.



回答4:

On my tests, it only changes the hash tag:

E.g. the real URL is:

http://www.facebook.com/photo.php?fbid=x&set=z

and clicking next results in:

http://www.facebook.com/photo.php?fbid=x&set=z#!/photo.php?fbid=y&set=z&pid=pid&id=id

The part after the hash is setup for Google AJAX crawl. But for the purpose of the browser, it's just a hash (fragment identifier).