Search code examples
javascripthtmlpage-refresh

Automatic HTML page refresh preserving scroll position, working with anchors


I have a web service generating a html and I need it to be automatically refreshed in the browser every 10 seconds. I've done it simply with <meta http-equiv="refresh" content="10"> and it worked fine, preserving the scroll position (at least in Firefox).

Then I added some internal linking within the page, using e.g. <a href="#foo">Foo</a> to link to <a name="foo"/>. After clicking such a link, I jump to the appropriate section and #foo is appended to the URL in the address bar, as expected. But if the automatic refresh happens now, #foo disappears from the address bar and the page scrolls to the top after refresh.

Is there some way to keep automatically refreshing the page, keeping the scroll position and being able to use internal linking without breaking it all?

UPDATE

I've tried to change the meta to <meta http-equiv="refresh" content="10;url=page.html#foo"> (without Javascript for now, just directly this value to see if it works). I open the page as page.html, it refreshes once as page.html#foo and then it stops. Why doesn't it keep refreshing?


Solution

  • It's unfortunate that the whole page needs to be reloaded, and you're not able to just do an AJAX call to get the data.

    Since your page needs to be refreshed every time, you could consider storing the scroll position in local storage and reading it when the page loads again. That code might look something like this:

    document.addEventListener("DOMContentLoaded", function(event) { 
        var scrollpos = localStorage.getItem('scrollpos');
        if (scrollpos) window.scrollTo(0, scrollpos);
    });
    
    window.onbeforeunload = function(e) {
        localStorage.setItem('scrollpos', window.scrollY);
    };
    

    If you would like to refresh the page and keep the anchor link, you can use JavaScript instead of a meta refresh tag:

    setTimeout(function() {
        location.reload();
    },10000);