开发者

Detect Browser Refresh in Javascript

I am curious if there is a way to detect the browser refresh event in javascript specifically. We are using the jQuery.address plugin to provide forward and back button functionality to AJAX functions. The problem I am facing is that this plugin does not seem to detect if the user has refreshed the p开发者_JAVA技巧age.

This code is executed each time the user moves forward or back in the browser history. I would also like it to exexute when the user refreshes.

 $.address.init(function(event) {
}).change(function(event) {

        SummaryDiv.SwapPanels(newPanelID);
    }

Any ideas?


Along these lines, I had a page whose behavior I didn't want to repeat if refreshed, so I changed the hash programmatically as described in this answer.

checkRefresh: function() {
    if (document.location.hash === '#visited') {
        console.log('Refreshed');
        return true;
    } else {
        document.location.hash = 'visited';
        return false;
    }
}

UPDATE

I found that at least Mobile Safari would ignore the hash if the refresh occurred automatically (e.g. page data expunged from cache before being viewed again). I ended up using a more complex solution described here.


A naive attempt of mine would be to simply store the current state into some cookie after each change and simply load them again on each page load.


Found this on the web for you...

Has both a javascript clever method along with a cookies method.

http://www.tedpavlic.com/post_detect_refresh_with_javascript.php


On a page refresh, the javascript is also reloaded. So couldn't you specify what you want to happen directly in jQuery's ready method?


I was able to force the change event code to run on refresh by

  window.onload = $.address.update(function(){    
...
})


In javascript you can do this:

page1.html

<script>
   localStorage.removeItem('setear1')
</script>

page2.html

<script>
    addEventListener('DOMContentLoaded', () => {
        let vengoDeLaPaginaAnterior = localStorage.getItem('setear1')
        if (vengoDeLaPaginaAnterior === null) {
            localStorage.setItem('setear1', 1)
        } else {
            document.location.href = 'page1.html'
        }
    })
</script>

then: if user refresh page, return to previus page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜