Nick
Nick

Reputation: 19684

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 page.

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?

Upvotes: 15

Views: 59058

Answers (6)

Eugim
Eugim

Reputation: 11

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.

Upvotes: 1

Ben Flynn
Ben Flynn

Reputation: 18932

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.

Upvotes: 9

Nick
Nick

Reputation: 19684

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

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

Upvotes: 1

Capt Otis
Capt Otis

Reputation: 1260

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

Upvotes: 4

chmod222
chmod222

Reputation: 5722

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.

Upvotes: 5

kingjeffrey
kingjeffrey

Reputation: 15290

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?

Upvotes: 1

Related Questions