简体   繁体   中英

How to use preventBack() to refresh a page when pressing back button?

This code forwards if pressing back button in both iOS & Android:

    <script type = "text/javascript" >
    function preventBack(){window.history.forward();}
    setTimeout("preventBack()", 0);
    window.onunload=function(){null};
    </script>

This code refreshes a page when hitting or swiping back in iOS but not working in android:

    <input type="hidden" id="refreshed" value="no">
    <script type="text/javascript">
    onload=function(){
    var e=document.getElementById("refreshed");
    if(e.value=="no")e.value="yes";
    else{e.value="no";location.reload();}
    }
    </script>

So can we make a code that works in both iOS & android to refresh when hitting back or swiping back using preventBack() function. Is it possible?

Use the below code, this will helps you to stop click back and reload the page too.

function preventBack() {
  history.pushState(null, null, document.URL);
  window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
    location.reload();
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM