How does FB refresh the page without reloading (xmlHttpRequest), but does the back button still work?

How does FB refresh the page without reloading it (xmlHttpRequest), but the back and forward buttons still work as usual?

This is not about using history.pushState() methods. PushState() only modifies the URL string, but does nothing to get the previous page after clicking the back button. So something else.

Here is my code and example.

I have such a site (look at the picture below). Header-div and Content-div. In the beginning, when you first open it, the url is mysite.com/page1.php. . I want to change the content in the Content-div without reloading the page. Just new information should appear in the Content-div. And the url should change to mysite.com/page2.php .

Here is the HTML code.

 <div id="content"></div> <a href="" id="relaodLink">Reload Content</a> 

Here is the JS code for it.

 document.getElementById("relaodLink").onclick = function() { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", "page2.php", true); xmlHttp.send(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { document.getElementById("content").innerHTML = xmlHttp.responseText; } } return false; } 

Thus, the title should not reload after clicking relaodLink , only the contents of the Content-div are changed. And most importantly: the url should change as if the page really had a reload. The back button allows you to return to mysite.com/page1.php , and then the next button allows you to return to mysite.com/page2.php . With history.pushState() methods, this does not work. But in FB, the Back and Forward buttons work fine. How to do it?

a busy cat
(source: ljplus.ru )

+4
source share
1 answer

This is a great question. If you notice, you may notice that the back and forward buttons will work in gmail, although it is completely built on Ajax.

The back and forward buttons of the browser work to save what is in the address bar. Therefore, in Ajax, if you never change what is in the address bar, it is not included in the history, and therefore the "Back" and "Forward" buttons do not work.

For this to work, you need to constantly add something to the address bar.
For example: In gmail ,
When you click the Inbox button - https://mail.google.com/mail/ tab = mm # inbox
When you click on an asterisk - https://mail.google.com/mail/ tab = mm # starred
When you click Sent - https://mail.google.com/mail/ tab = mm # sent

Thus, gmail continues to add to the address bar. Consequently, the story is preserved. The same thing happens with facebook . Although the page does not refresh, the location in the address bar has changed - here it is!

Hope this helps you!

+5
source

Source: https://habr.com/ru/post/1389030/


All Articles