Reload an HTML page just once using JavaScript

2019-01-12 08:03发布

问题:

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 keep in mind that i am using iframe so this is not possible to to use the below types code:

<script language=" JavaScript" ><!--
function MyReload()
{
window.location.reload();
}
//--></script>

<Body onLoad=" MyReload()" > 

the above code not worked for me

but the below code is work good but the problem is that i need it to loads once

<BODY BGCOLOR=#FFFFFF background="../images/Index_04.jpg" onLoad="history.go(0)" >

note: I am using 2 iframes when user click on main page link a page loads in iframe than i want to reload the whole page with current iframe page.

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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>