Search code examples
facebookxmlhttprequestback-buttonpage-refresh

How FB refreshes the page without reloading it (xmlHttpRequest) but Back button still works?


How FB refreshes the page without reloading it (xmlHttpRequest) but Back/Forward Buttons still work as usual?

It's not about using history.pushState() methods. PushState() only changes URL-string but does nothing to get previous looking page after you click Back Button. So it's smth different.

Here's my code and example.

I have such site (look at the pic below). Header-div and Content-div. At the begining when you first time open it, the URL is mysite.com/page1.php. I want to change content in Content-div without reloading page. Just new info should appear in Content-div. And the URL should change to mysite.com/page2.php.

Here's HTML-code.

<div id="content"></div>

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

Here's JS-code to 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;
}

So Header should not reload after pressing relaodLink, just content in Content-div changes. And most important: URL should change like page was really reloaded. Back Button allows to go to mysite.com/page1.php and then Forward Button allows to go back to mysite.com/page2.php again. With history.pushState() methods it doesn't work. But in FB Back and Forward Buttons work fine. How to make it?

a busy cat
(source: ljplus.ru)


Solution

  • This is an excellent question. If you observe, you can notice that the back buttons and forward buttons will work in gmail also though it is completely built on Ajax.

    The browser back and forward buttons work on storing what is there in the address bar. So in Ajax, if you never change what is there in the address bar, it doesn't go into the history and hence back and forward buttons don't work.

    For this to work, you need to append something to the address bar constantly.
    For example : In gmail,
    When Inbox is clicked - https://mail.google.com/mail/?tab=mm#inbox
    When Starred is clicked - https://mail.google.com/mail/?tab=mm#starred
    When Sent is clicked - https://mail.google.com/mail/?tab=mm#sent

    So in this way, gmail keeps appending to address bar. Hence history is preserved. The same goes with facebook also. Though the page is not refreshed, the location in address bar changed - that's the key here !!

    I hope it helps you !