Reload an HTML page just once using JavaScript

后端 未结 4 1769
梦毁少年i
梦毁少年i 2020-12-02 01:40

How can I reload an HTML base web page only once? I am using history.go(0); with function onLoad in body tag but i want to run it only once. Please

相关标签:
4条回答
  • 2020-12-02 02:04
     <script type="text/javascript">
            $(document).ready(function(){
    
                //Check if the current URL contains '#' 
                if(document.URL.indexOf("#")==-1)
                {
                    // Set the URL to whatever it was plus "#".
                    url = document.URL+"#";
                    location = "#";
    
                    //Reload the page
                    location.reload(true);
    
                }
            });
        </script> 
    

    Due to the if condition the page will reload only once. Hope this will help.

    0 讨论(0)
  • 2020-12-02 02:05

    Here is another solution which works for me using localStorage. In this solution we don't need to modify existing url.

    <script type='text/javascript'>
     (function()
     {
      if( window.localStorage ){
        if(!localStorage.getItem('firstReLoad')){
         localStorage['firstReLoad'] = true;
         window.location.reload();
        } else {
         localStorage.removeItem('firstReLoad');
        }
      }
     })();
    </script>
    
    0 讨论(0)
  • 2020-12-02 02:10

    You could use a querystring at the end of the page url (e.g. ?r), and check for it before redirecting, as if it exists, the redirect is already done.

    if(window.location.href.substr(-2) !== "?r") {
      window.location = window.location.href + "?r";
    }
    

    Disclaimer: I agree with others that you probably have a better solution - and should never need to refresh 'just once'.

    Explanation of use

    At the bottom of your page, just above the </body> you should put this:-

    <script type="text/javascript">
       if(window.location.href.substr(-2) !== "?r") {
          window.location = window.location.href + "?r";
        }
    </script>
    

    That's it.

    0 讨论(0)
  • 2020-12-02 02:17

    The only way I can think of to do this is by using cookies (or if your on the right platform, sessions) and flag the first time it has reloaded, variables might also work in this case, because we're speaking about IFRAME, but I have never tried such thing.

    0 讨论(0)
提交回复
热议问题