Search code examples
javascriptjqueryonbeforeunloadhashchange

Change location.hash on unbeforeunload


I have a page which is generated using JavaScript. I want to store the $(window).scrollTop() value in a hash (like #position=xxx) so when the page is refreshed and the items are generated again, the user can continue scrolling from where they left off.

I'm trying to modify the hash on beforeunload, which does not seem to work. The first part of the function below tries to change the hash, and the second part is taking care of the modification of the scrollTop on page load. The second part works fine, I'm only stuck with the first part.

$(window).on('beforeunload',function(){
    window.location.hash = "position="+$(window).scrollTop();
}).on('load hashchange',function(){
    var scrollregex = /^position=(\d+)$/,
        hash = window.location.hash.substring(1);
    if (scrollregex.test(hash)) $(window).scrollTop(parseInt(hash.match(scrollregex)[1]));
});

Is there a different event for this, or otherwise how can I change the hash when the user triggers a refresh?


Solution

  • I ended up ditching the hash idea and going with a sessionStorage based approach. I wrote my own wrapper for session/local storage which I use in the following example.

    $(window).on('beforeunload',function(){
        var scrltop = $(window).scrollTop();
        if (scrltop > 0) SStorage.set('position',scrltop);
        else SStorage.del('position');
    }).on('load',function(){
        if (SStorage.has('position')){
            var pos = parseInt(SStorage.get('position'));
            if (!isNaN(pos) && $(window).scrollTop() === 0) $(window).scrollTop(pos);
        }
    });