JavaScript - bfcache/pageshow event - event.persisted always set to false?

后端 未结 3 1363
灰色年华
灰色年华 2021-02-02 01:59

In a standard Java / SpringMVC / JSP / jQuery web-app, I\'m trying to detect a \"Back\" (or history.go(-1)) event, in order to refresh (AJAX) a summary component/panel content w

3条回答
  •  一整个雨季
    2021-02-02 02:29

    I have found hidden input buttons are not a reliable solution since they may hold the wrong value when the user navigates back to the page and then hits refresh. Some browsers (Firefox) retain input values on refresh so every time the user hits refresh it will refresh again since the input button holds the wrong value. This is a typical scenario for forums (user views a topic, hits the back button to go back to the list of topics, and may continue to hit refresh to check if there are new topics).

    As noted by Grégoire Clermont, event.persisted is buggy in chrome (and IE) and this still hasn't been fixed for either browser as of Feb 2017. The good news is you can rely on window.performance.navigation.type == 2 for chrome and IE. Ironically Firefox is unreliable for the latter but it shouldn't matter since it is reliable for event.persisted. The following code worked for me:

    if (document.addEventListener) {
        window.addEventListener('pageshow', function (event) {
            if (event.persisted || window.performance && 
                window.performance.navigation.type == 2) 
            {
                location.reload();
            }
        },
       false);
    }
    

提交回复
热议问题